1 内部类
class TestInnerClass{
public static void main( String[] args ){
Parcel p = new Parcel();
p.testShip();
Parcel.Contents c = p.new Contents(33); // 类型定义需要用 Parcel, 但后面 new 的时候不需要
Parcel.Destination d = p.new Destination( "Hawii" ); // 还需要注意 new 前面的 p.
Parcel.Contents cc = new Parcel().new Contents(44); // ok,内部类的 new 前面一定要有一个对象实例
p.setProperty( c, d );
p.ship();
}
}
class Parcel {
private Contents c;
private Destination d;
class Contents {
private int i;
Contents( int i ){ this.i = i; }
int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) {label = whereTo;}
String readLabel() { return label; }
}
void setProperty( Contents c, Destination d ){
this.c =c; this.d = d;
}
void ship(){
System.out.println( "move "+ c.value() +" to "+ d.readLabel() );
}
public void testShip() {
c = new Contents(22);
d = new Destination("Beijing");
ship();
}
}
- 内部类可以直接访问外部类的字段和方法,即使是 **
private
** 的 - 如果内部类中有与外部类同名的字段或名字,可以使用
OuterClass.
this
.method()
访问外部类的方法和字段
【内部类的修饰符】
- 访问控制符:
public
,protected
,默认
,private
- 注意: 外部类只能使用
public
或者默认
进行修饰
- 注意: 外部类只能使用
final
,abstract
static
修饰符
class TestInnerStatic {
public static void main(String[] args) {
A.B a_b = new A().new B(); // ok
A a = new A();
A.B ab = a.new B();
Outer.Inner oi = new Outer.Inner(); // 这里 new 前面不需要对象实例
//Outer.Inner oi2 = Outer.new Inner(); //!!!error
//Outer.Inner oi3 = new Outer().new Inner(); //!!! error
}
}
class A {
private int x;
void m(){
new B();
}
static void sm(){
//new B(); // error!!!!
}
class B {
B(){ x=5; }
}
}
class Outer {
static class Inner {
}
}
2 局部类
在类的方法(Java 中所有的方法都定义在类中)中定义的类,称为“方法中的局部类”。
class TestInnerInMethod {
public static void main(String[] args) {
Object obj = new Outer().makeTheInner(47);
System.out.println("Hello World!" + obj.toString() );
}
}
class Outer {
private int size = 5;
public Object makeTheInner( int localVar ) {
final int finalLocalVar = 99;
class Inner {
public String toString() {
return ( " InnerSize: " + size +
// " localVar: " + localVar + // Error!
" finalLocalVar: " + finalLocalVar
);
}
}
return new Inner();
}
}
3 匿名类
匿名类( anonymous class ) 是一种特殊的内部类。
- 没有类名,在定义类的时候同时生成一个实例(相当于定义 +
new
) - “一次性使用”的类
class TestInnerAnonymous
{
public static void main(String[] args)
{
Object obj = new Outer().makeTheInner(47);
System.out.println("Hello World!" + obj.toString() );
}
}
class Outer
{
private int size = 5;
public Object makeTheInner( int localVar )
{
final int finalLocalVar = 99;
return new Object() {
public String toString() {
return ( " InnerSize: " + size +
" finalLocalVar: " + finalLocalVar
);
}
};
}
}