为什么需要内部类
内部类提供了某种进入外围类的窗口,解决“多重继承”的问题
每个内部类都能够独立地继承字一个接口的实现,所以无论外围类是否已经继承了某个接口的实现,对于内部类都是没有影响的
interface A {} interface B {} calss X implements A,B {} calss Y implements A { B makeB() { return new B() {}; } }
使用.this
和.new
如果需要生成对外部类对象的引用,可以使用内部类的名字后面紧跟
.this
public class DotThis{ void f(){System.out.println("DotThis.f()");} public class Inner{ public DotThis outer() { // return DotThis class return DotThis.this; } } public Inner inner() { return new Inner(); } public static void main(String[] args){ DotThis dt = new DotThis(); DotThis.inner dti = dt.inner(); dti.out.f(); } } /* out DotThis.f() */
创建某个内部类对象 必须先创建外部类,再使用
.new
来创建内部类public class DotNew { public class Inner {} public static void main(String[] args) { DotNew dn = new DotNew(); DotNew.Inner dni = dn.new Inner(); } }
匿名内部类
创建一个继承自基类的匿名类的对象(匿名内部类末尾
;
)//无参 public class Parcel7 { //contents() 方法将返回值的生成与表示这个返回值的类的定义结合在一起 public Contents contents () { return new Contents () { privatte int i=11; public int value () {return i;} }; } public static void main (String[] args) { Parcel7 p = new Parcel7(); Contents c = p.contents(); } } //含参 public class Parcel8 { public Wrapping wrapping (int x){ return new Wrapping(x) { public int value() { return super.value() *47; } }; } public static void mian(Stringp[] args) { Parcel8 p =new Parcel8(); Wrapping w = p.wrapping(10); } }
实例初始化实现内部类的构造器(变量必须是
fianl
)public class Parcell0 { public Destination destination (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;} }; } }
内部类的继承
calss WithInner {
calss Inner {}
}
public calss InheritInner extends WithInner.Inner {
//! InheritInner() //Won't complie
InheritInner (WithInner wi) {wi.super();}
}