java中的嵌套类

时间:2014-10-03 12:10:35

标签: java nested-class

有谁能告诉我为什么下面的代码不起作用?

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

5 个答案:

答案 0 :(得分:3)

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

你究竟想做什么?

答案 1 :(得分:2)

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

例如

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

你可以像这样创建Object Z,因为内部类是 static

X.Y.Z obj=new X.Y.Z();

答案 2 :(得分:1)

以下将编译:

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

或者您可以导入LittleNested

import <yourpackage>.NestedClassPrac.Nested.LittleNested;

基本上,您可以在main内访问NestedClassPracNested内同一层级的任何内容,而无需导入。这样您就可以访问LittleNested。但是,LittleNested不是分层次地处于同一级别; Nested位于{{1}}内。因此,您需要导入。

答案 3 :(得分: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();
    }
}

从main方法中只能引用Nested类。您可以在Nested Classes - Java Tutorial

了解相关信息

答案 4 :(得分:0)

你应该这样访问:

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