札记
在清理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