Java编程思想(2nd)学习笔记(8)-3

王朝java/jsp·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

3. 如何产生innerclass对象的总结

3.1non-static内隐类

1) 在enclosingclass的non-static函数中可以直接通过new来产生

2) 在enclosingclass的static函数或其它的class中,必须同时存在一个enclosingclass对象(原因在上面2.1已说明)。

interface Contents{

int value();

}

class Parcel1{

protected class PContents implements Contents{

public int value() { return 1; }

}

public Contents cont(){

//在non-static函数中直接通过new来产生PContents class对象

return new PContents();

}

public static void test(String[] args){

Parcel1 p1 = new Parcel1();

//在static函数中通过外部类Parcel1对象来产生

Contents c1 = p1.cont(); //调用函数

c1 = p1.new PContents();//通过new

}

}

public class ExplicitStatic{

public static void main(String[] args){

//通过外部类Parcel1对象来产生

Parcel1 p1 = new Parcel1();

Contents c1 = p1.cont(); //调用函数

c1 = p1.new PContents(); //通过new

}

}

3.2static内隐类

1) 除了可用产生non-static内隐类对象的方法来产生之外,也可以不通过已存在一个enclosingclass对象来产生。

interface Contents{

int value();

}

class Parcel1{

protected static class PContents implements Contents{

public int value() { return 1; }

}

public Contents cont(){

//在non-static函数中直接通过new来产生PContents class对象

return new PContents();

}

public static Contents cont1(){

//在static函数中直接通过new来产生PContents class对象

return new PContents(); //(1)

}

public static void test(String[] args){

Parcel1 p1 = new Parcel1();

//在static函数中通过外部类Parcel1对象来产生

Contents c1 = p1.cont(); //调用函数

c1 = p1.new PContents(); //通过new

//在static函数中直接通过new来产生PContents class对象

c1 = new PContents(); //(1)

}

}

public class ExplicitStatic{

public static void main(String[] args){

//通过外部类Parcel1对象来产生

Parcel1 p1 = new Parcel1();

Contents c1 = p1.cont(); //调用函数

c1 = p1.new PContents(); //通过new

//直接产生

c1 = Parcel1.cont1(); //(2)

}

}

上面的(1)和9(2)中的代码只有在Pcontentsclass为static时才能通过。(1)不能通过的原因见2.1。

2. innerclass的继承

1) innerclass可被继承。innerclass的drivedclass的drfault构造函数必须传入一个reference指向outerobject,并在构造函数中调用outerclass的构造函数。

class WithInner{

class Inner{}

}

class InheritInner extends WithInner.Inner

{

//InheritInner(){} 编译错误

InheritInner(WithInner wi) { wi.super(); }

}

public class ExplicitStatic{

public static void main(String[] args){

WithInner wi = new WithInner();

InheritInner ii = new InheritInner(wi);

}

}

2) 覆写innerclass不具备多态特性。

class Egg{

class Yolk{

public Yolk(){

System.out.println("Egg.Yolk()");

}

}

private Yolk y;

public Egg(){

System.out.println("New Egg()");

y = new Yolk(); //(1)

}

}

class BigEgg extends Egg{

//(2)尝试覆写innerclass

class Yolk{

public Yolk(){

System.out.println("BigEgg.Yolk()");

}

}

}

public class ExplicitStatic{

public static void main(String[] args){

new BigEgg(); //(3)

}

}

结果为:

New Egg()

Egg.Yolk()

在(2)中我们尝试覆写innerclass。当通过(3)产生一个BigEgg时,会调用Egg的构造函数。在Egg的构造函数的(1)处产生的是Egg.Yolkclass对象,而不是子类BigEgg.Yolkclass对象。

**:如上所示,上述两个innerclass是完全独立的个体,各有其专属的命名空间。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航