站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题Java编程思想(2nd)学习笔记(8)-3

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

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

3. 如何产生inner class对象的总结
3.1 non-static内隐类
1) 在enclosing class的non-static函数中可以直接通过new来产生
2) 在enclosing class的static函数或其它的class中,必须同时存在一个
enclosing class对象(原因在上面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.2 static内隐类
1) 除了可用产生non-static内隐类对象的方法来产生之外,也可以不通过已存在
一个enclosing class对象来产生。
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)中的代码只有在Pcontents class为static时才能通过。(1
)不能通过的原因见2.1。
2. inner class的继承
1) inner class可被继承。inner class的drived class的drfault构造
函数必须传入一个reference指向outer object,并在构造函数中调用outer 
class的构造函数。
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) 覆写inner class不具备多态特性。
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)尝试覆写inner class
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)中我们尝试覆写inner class。当通过(3)产生一个BigEgg时,会调用Egg
的构造函数。在Egg的构造函数的(1)处产生的是Egg.Yolk class对象,而不是子

BigEgg.Yolk class对象。
**:如上所示,上述两个inner class是完全独立的个体,各有其专属的命名空间。
↑返回目录
前一篇: Java编程思想(2nd)学习笔记(9)-1
后一篇: Java编程思想(2nd)学习笔记(8)-2