您的位置:首页 > 编程语言 > Java开发

Java—内部类

2014-04-15 20:04 423 查看
It's possible to please a class definition within another class definition. 内部类即定义在另一个类的内部的类。

When you create an inner class, an object of that inner class has a link to the enclosing object that made it, and so it can access the members of that enclosing object-- without any special qualifications. In addition, inner classes have access rights to
all the elements in the enclosing class. 一个内部类对象自动的连接到创建它的外部类对象上,并且,在内部类中,有权限访问外部类的各成员。

编译器会在内部类对象中,存储一个其外部类对象的引用。在内部类中,.this表示引用到其外部类对象。例如:

public class DotThis {
void f () { System.out.println ("DotThis.f ()"); }

public class Inner {
public DotThis outer () {
// DotThis.this 获取外部类的对象的引用
return DotThis.this;
}
}
}

class DotNew {
public static void main (String[] args) {
DotThis dt = new DotThis();
// 通过外部类对象创建内部类对象
DotThis.Inner dti = dn.new Inner();
}
}


由于内部类对象要连接到外部类对象,因此在创建内部类对象之前,外部类对象必须已经存在,也就是说,不可能在没有外部类对象的情况下,创建其内部类对象。

内部类访问权限

通常类只能是public或者包访问权限,但内部类可以是public、private、protected以及包访问权限。

匿名内部类

If you're defining an anonymous inner class and want to use an object that's defined outside the anonymous inner class, the compiler requires that the argument reference be final. 如果你在匿名内部类使用一个在匿名内部类外部定义的对象,那么要求传递给匿名内部类的参数是final的。否则将出现编译错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: