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

来源:互联网 发布:专业制谱软件 编辑:程序博客网 时间:2024/05/16 11:48
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不需要先建立外部对象)


原创粉丝点击