2014-10-03 112 views
0

任何人都可以告诉我为什么下面的代码不起作用?java中的嵌套类

public class NestedClassPrac { 
    public static class Nested { 
     public void sayHello() { System.out.println("First nested class~");} 
     public static class LittleNested { 
      public void sayHello() { System.out.println("this is why we are nested class");} 
     } 
    } 


    public static void main(String[] args) { 
     Nested a = new Nested(); 
     a.sayHello(); 
     LittleNested b = new LittleNested(); 
     b.sayHello(); 
    } 
} 

错误信息:

NestedClassPrac.java:13: cannot find symbol 
symbol : class LittleNested 

location: class NestedClassPrac 
     LittleNested b = new LittleNested(); 
     ^

NestedClassPrac.java:13: cannot find symbol 

symbol : class LittleNested 

location: class NestedClassPrac 
     LittleNested b = new LittleNested(); 
          ^
2 errors 

回答

2

LittleNested只有通过Nested类访问你不能直接访问它不使用Nested作为访问类的任何其他静态部件。您可以访问内部静态类相同(即,方法,可变)。

对于实施例

class X{ 
    static class Y{ 
     static class Z{ 
      Z(){ 
       System.out.println("Inside Z"); 
      } 
     } 
    } 
} 

可以创建Z这样作为内部类Object静态

X.Y.Z obj=new X.Y.Z(); 
3
 Nested.LittleNested b = new Nested.LittleNested(); 

究竟是你想做些什么?

+0

哇,谢谢!我知道了。 – shanwu 2014-10-03 12:15:55

1

下面将编译:

Nested.LittleNested b = new Nested.LittleNested(); 

,或者你可以导入LittleNested

import <yourpackage>.NestedClassPrac.Nested.LittleNested; 

基本上,你有内NestedClassPrac在同一层级内main获得任何东西,而不需要一个进口。这使您可以访问Nested。但是,LittleNested不是分层次的同一级别; LittleNestedNested之内。因此,您需要导入。

0

你应该像这样访问:

OuterClass.InnerClass1.InnerClass2...InnerClassN obj=new OuterClass.InnerClass1.InnerClass2...InnerClassN(); 
obj.method(); 
1

您的代码不从,你需要参考LittleNested子内部类,包括封闭类名称的主要方法范围,因为工作:

public class NestedClassPrac { 
    public static class Nested { 
     public void sayHello() { System.out.println("First nested class~");} 
     public static class LittleNested { 
      public void sayHello() { System.out.println("this is why we are nested class");} 
     } 
    } 


    public static void main(String[] args) { 
     Nested a = new Nested(); 
     a.sayHello(); 
     Nested.LittleNested b = new Nested.LittleNested(); 
     b.sayHello(); 
    } 
} 

从主要方法只能引用嵌套类。你可以在Nested Classes - Java Tutorial