java基础——1.内部类

时间:2023-03-09 17:30:31
java基础——1.内部类
  • 内部类创建

从外部类的非静态方法之外(?=静态方法)的任意位置创建某个内部类的对象,要加入外部类的名字,OuterClassName.InnerClassName

public class Parcel2 {

class Contents {

private int i = 11;

public int value() { return i; }

}

class Destination {

private String label;

Destination(String whereTo) {

label = whereTo;

}

String readLabel() { return label; }

}

public Destination to(String s) {

return new Destination(s);

}

public Contents contents() {

return new Contents();

}

public void ship(String dest) {

Contents c = contents();

Destination d = to(dest);

System.out.println(d.readLabel());

}

public static void main(String[] args) {

Parcel2 p = new Parcel2();

p.ship("Tasmania");

Parcel2 q = new Parcel2();

// Defining references to inner classes:

Parcel2.Contents c = q.contents();

Parcel2.Destination d = q.to("Borneo");

}

}

  • 链接到外部类

内部类拥有其外围类的所有元素的访问权(包括private):当某个外围类的对象创建了一个内部类对象时,此内部类必定会捕获一个指向那个外围类对象的引用

  • 使用.this与.new

.this在内部类生成外部类对象的引用,使用:外部类名字.this。如在内部类Inner内创建外部类DotThis对象的引用

.new在外部类的某内部类外的其他地方创建其此内部类的对象,使用:外部类对象名字.new.如在main()方法创建内部类Inner的对象

public class DotThis {

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

public class Inner {

public DotThis outer() {

return DotThis.this;

// A plain "this" would be Inner's "this"

}

}

public Inner inner() { return new Inner(); }

public static void main(String[] args) {

DotThis dt = new DotThis();

DotThis.Inner dti = dt.inner();

dti.outer().f();

}

}

public class DotNew {

public class Inner {}

public static void main(String[] args) {

DotNew dn = new DotNew();

DotNew.Inner dni = dn.new Inner();

}

}