Chinaunix首页 | 论坛 | 博客
  • 博客访问: 542568
  • 博文数量: 855
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-16 19:08
文章分类

全部博文(855)

文章存档

2011年(1)

2008年(854)

我的朋友

分类:

2008-10-16 19:16:47

    JAVA从JDK1.1开始引入了内部类,可以参见代码,感觉好处就是设计类的时候可以偷懒,呵呵。主要是可以引用类的内部其他元素,差不多是把这个内部类当成原类的元素。还有可以隐藏类的一些设计细节,好处还是很多的。

定义两个接口

package interfacepackage;

public interface Destination {
 String readLabel();
}

package interfacepackage;

public interface Contents {

 int value();

}

一个类,并且加有测试代码

package debug;

import interfacepackage.Contents;
import interfacepackage.Destination;

public class Tester {
 private int valueRate = 2;

 private class PContent implements Contents {
  private int i = 11 * valueRate;

  public int value() {
   return i;
  }
 }

 protected class PDestination implements Destination {
  private String label;

  private PDestination(String whereTo) {
   label = whereTo;
  }

  public String readLabel() {
   return label;
  }
 }

 public Destination dest(String s) {
  return new PDestination(s);
 }

 public Contents cont() {
  return new PContent();
 }
 public static void main(String args[])
 {
  Tester p = new Tester();
   Contents c = p.cont();
   System.out.println(c.value());
   Destination d = p.dest("天外水火");
   System.out.println(d.readLabel());
   System.out.println("done");
 }
}
   上面的代码是内部动态类,那么内部静态类是否也可以呢?答案是可以的,但是静态内部类是无法引用类的其他非静态元素的,例如上例中的PContent 内部类如果改为static类,是无法引用valueRate 属性的,这样是会报编译错误的,但是如果valueRate 如果也改为static是可以运行的。

【责编:Peng】

--------------------next---------------------

阅读(191) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~