static inner class和非static inner class的实例化问题

package innerclasses; 
 
public class E18_NestedClass { 
 static class Nested { 
    void f() { System.out.println("Nested.f"); } 
  } 
  public static void main(String args[]) { 
    Nested ne = new Nested(); 
    ne.f(); 
  } 
} 
 
class Other { 
  // Specifying the nested type outside 
  // the scope of the class: 
  void f() { 
    E18_NestedClass.Nested ne = 
      new E18_NestedClass.Nested(); 
  } 
} /* Output: 
Nested.f 
*///:~ 

1: static inner class

当在同一个class内实例化内部类的话,只简单new就可以了。

当在另一个class内的化,就需要写清楚包含内部类的类名,如 Class.InnerClass = new Class.InnerClass();

(You can refer to just the class name when inside the method of a class with a defined nested (static inner) class, but outside the class, you must specify the outer class and nested class, as shown in Other, above.  )

=================================================================================================='

public class Test20 {
    public static void main(String[] args) {
	Class2 c = new Class2();
	Class2.Inner i = c.new Inner();
	i.f();
    }
}

class Class2 {
    class Inner {
	void f() {
	    System.out.println("Interface1 -> Inner -> f()");
	}
    }
}



2:非static inner class


http://bbs.bccn.net/thread-168190-1-1.html

First first = new First();
First.Second second = first.new First();
First.Second.Third third = second.new Third();

因为内部类中要保存外部类的一个引用,所以你先要生成外部类的对象。然后通过这个外部类的对象去创建内部类的对象。(static inner class不需要先建立外部对象)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值