java中的嵌套类
问题描述:
任何人都可以告诉我为什么下面的代码不起作用?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
答
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();
答
Nested.LittleNested b = new Nested.LittleNested();
究竟是你想做些什么?
答
下面将编译:
Nested.LittleNested b = new Nested.LittleNested();
,或者你可以导入LittleNested
import <yourpackage>.NestedClassPrac.Nested.LittleNested;
基本上,你有内NestedClassPrac
在同一层级内main
获得任何东西,而不需要一个进口。这使您可以访问Nested
。但是,LittleNested
不是分层次的同一级别; LittleNested
在Nested
之内。因此,您需要导入。
答
你应该像这样访问:
OuterClass.InnerClass1.InnerClass2...InnerClassN obj=new OuterClass.InnerClass1.InnerClass2...InnerClassN();
obj.method();
答
您的代码不从,你需要参考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
哇,谢谢!我知道了。 – shanwu 2014-10-03 12:15:55