理解-java内部类

札记
在清理2017年度清单,inbox zero 博客清单时,发现自己遗留了“java 内部类”这篇文档,自己认真回忆后发现确实记忆不太清楚,因此该文档尽快补写。

正文
在java(java class)中类内部声明的类,都叫嵌套类(nested class),区别在于如果没有static 修饰,称为内部类(inner class)。

嵌套类指所有的声明在别的类或接口中的类,无论有没有static修饰

A top level class is a class that is not a nested class.A nested class is any class whose declaration occurs within the body of another class or interface.

内部类是nested class的一种特例,是没有显式或隐式被static修饰的nested class

Inner Classes and Enclosing InstancesAn inner class is a nested class that is not explicitly or implicitly declared static.An inner class may be a non-static member class (§8.5), a local class (§14.3), or an anonymous class (§15.9.5). A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

使用说明
本文先不讨论java引入嵌套类存在的意义,更多的讨论一下嵌套类与内部的调用方式之间的区别。

class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}

对于静态嵌套类而言,嵌套类属于独立存在的类,调用方式跟传统的静态成员调用方式类似

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

但是对于内部类而言,调用方式更类似于于内部的成员调用

OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();

且内部类作为内部成员可以访问类内部的其他的成员,但是静态前台类则不可以实现,具体如下:

public class Main {

    private int x = 1;
    public static class nestclass{
        private int x =2;
        private void nestclassTest(){
            System.out.println("this.x = " +this.x);
            /*outerclass is a non-static class, nestedclass cannot access its member x*/
            //System.out.println("Main.x =" + Main.this.x);
        }

    }
     public class innerclass{
         int x = 3;
         public void innerclasstest(){
             System.out.println("this.x = " +this.x);
             System.out.println("Main.x =" + Main.this.x);
         }
    }
    public static void main(String[] args) {

        System.out.println("this.x = "+new Main().x);
        // static nested class
        Main.nestclass nestclass1 = new Main.nestclass();
        nestclass1.nestclassTest();

        //innerclass
        Main.innerclass innerclass1 = new Main().new innerclass();
        innerclass1.innerclasstest();

    }
}

输出如下:

main class: this.x = 1
nested class: this.x = 2
inner class: this.x = 3
inner class: Main.x =1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值