在Java 1.1 中,可将一个类定义置入另一个类定义中。这就叫作“内部类”。内部类对我们非常有用,因为利用它可对那些逻辑上相互联系的类进行分组,并可控制一个类在另一个类里的“可见性”。
内部类好处1:方便隐藏实现细节。比如一个接口,我写一个private的内部类实现这个接口,那么这个private的内部类只对所属的类可见。对于所有其他类都不可见。如下代码所示:(因为正常的类不能是private和protected,只允许为public和“友好的”)
package c07.parcel3;
public interface Destination {
String readLabel();
}
package c07.parcel3;
public class Parcel3 {
private class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
public String readLabel() {
return label;
}
}
public PDestination dest(String s) {
return new PDestination(s);
}
}
class Test {
public static void main(String[] args) {
Parcel3 p = new Parcel3();
Destination d = p.dest("Tanzania");
// 如下写法错误,不支持访问其他类私有的内部类
// Parcel3.PContents c = p.dest("Tanzania");
}
}
内部类好处2:缩小类的影响范围到方法体内,比如要解决一个复杂的问题,需要创建一个类,但是我不希望除开我这个方法别人能看到这个类。这个时候,我们可以将这个类建在我们的方法体内
package c07.parcel3;
public interface Destination {
String readLabel();
}
package c07.innerscopes;
import c07.parcel3.Destination;
public class Parcel9 {
public Destination dest(final String dest, final float price) {
return new Destination() {
private int cost;
{ //不能拥有构造函数,采用代码段来初始化
cost = Math.round(price);
if (cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() {
return label;
}
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.dest("Tanzania", 101.395F);
}
}
interface Selector {
boolean end();
Object current();
void next();
}
public class Sequence {
private Object[] o;
private int next = 0;
public Sequence(int size) {
o = new Object[size];
}
public void add(Object x) {
if (next < o.length) {
o[next] = x;
next++;
}
}
private class SSelector implements Selector {
int i = 0;
public boolean end() {
return i == o.length;
}
public Object current() {
return o[i];
}
public void next() {
if (i < o.length)
i++;
}
}
public Selector getSelector() {
return new SSelector();
}
public static void main(String[] args) {
Sequence s = new Sequence(10);
for (int i = 0; i < 10; i++)
s.add(Integer.toString(i));
Selector sl = s.getSelector();
while (!sl.end()) {
System.out.println((String) sl.current());
sl.next();
}
}
}
使用内部类的好处总结
* (1)在单独一个类里面表达一个控制框架应用的全部实施细节
* 从而完整的封装和那个实施有关的东西。也就是说把所有event都作为内部类来封装
* (2)内部类使我们具体的实施变得更加巧妙,因为可以方便的访问到外部类的任何成员
* 这样带来一定的便利。