Java 从入门到进阶之路(十六)

在之前的文章我们介绍了一下 Java 中类的多态,本章我们来看一下 Java 中类的内部类。

在 Java 中,内部类分为成员内部类和匿名内部类。

我们先来看一下成员内部类:

1、类中套类,外面的叫外部类,里面的叫内部类

2、内部类通常只服务于外部类,对外不具备可见性

3、内部类对象通常是在外部类中创建

4、内部类可直接访问外部类成员,包括私有的。因为内部类中有个隐式的引用指向创建它的外部类对象。

具体代码如下:

1 public class HelloWorld { 2 public static void main(String[] args) { 3 Mother mother = new Mother(); 4 mother.show(); 5 } 6 } 7 8 class Mother { // 外部类 9 private int age = 10; 10 11 void show() { 12 Son son = new Son(); // 可在外部类中创建 13 son.test(); 14 } 15 16 class Son { // 内部类 17 void test() { 18 System.out.println(age); // 10 19 System.out.println(Mother.this.age); // 10 隐式的引用指向创建它的外部类对象 20 System.out.println(this.age); // 编译错误 21 } 22 } 23 } 24 25 class Test { 26 void show() { 27 Mother mother = new Mother(); 28 Son son = new Son(); // 编译错误,内部类不具备可见性 29 } 30 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxwyp.html