`
leonmau
  • 浏览: 103162 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java内部类访问

    博客分类:
  • Java
 
阅读更多

当内部类为非静态时:

public class InnerClassTest {
    private static int i = 0;

    public class Test {
        private int i = 1;

        protected int add() {
            return i + i;
        }
    }

    public static void main(String[] args) {
        InnerClassTest.Test test2 = new InnerClassTest().new Test();
        System.out.println(test2.add());
    }
}
 

 当内部类为静态时:

public class InnerClassTest {
    private static int i = 0;

    public static class Test {
        private int i = 1;

        protected int add() {
            return i + i;
        }
    }

    public static void main(String[] args) {
        InnerClassTest.Test test2 = new InnerClassTest.Test();
        System.out.println(test2.add());
    }
}
 

 

简单分析: 内部类为非静态时,内部类必须属于某个外围类的对象,所以必须先new InnerClassTest()一个对象出来, 然后new Test()对象。当内部类为静态类时,不属于任何外部类,内部类不包含对外部类对象的引用,因此直接 new InnerClassTest.Test()对象

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics