最近看了一篇介绍 Java 内部类的文字, 发现之前对内部类的理解还不完整, 这里重新总结一下对 java 内部类的理解
内部类的种类?
非静态内部类 (Non-static nested class) 或者(inner class)
静态内部类(Static nested class)
非静态内部类(Non-static nested class)
非静态内部类是指一个类嵌套了另外一个类, 被嵌套的这个类可以访问封闭类 (outer class) 的成员变量, 因此通常也被称为 inner class
我们来看一个实例了解一下非静态内部类
- public class Animal {
- private String getType(int type) {
- if (type == 1) {
- return "birds";
- } else {
- return "mammal";
- }
- }
- class Chicken {
- String weigth;
- public int getPrice() {
- return 1000;
- }
- public String getType() {
- return Animal.this.getType(1);
- }
- }
- class Panda {
- String gender;
- public String getFrom() {
- return "ChengDu";
- }
- public String getType() {
- return Animal.this.getType(2);
- }
- }
- }
以上代码创建了一个 Animal 类, Animal 里面嵌套了 Pig 和 Panda 类, 所以 Pig 和 Panda 属于 Animal 的内部类, 而 Animal 相对于 Pig 和 Panda 类属于封闭类(也叫外部类), 所以, 在 Pig 和 Panda 可以调用 Animal 的成员变量以及成员方法, 下面看一下内部类的调用
- public class Main {
- public static void main(String[] args) {
- Animal animal = new Animal();
- Animal.Chicken pig = animal.new Chicken();
- System.out.println(pig.getPrice());
- System.out.println(pig.getType());
- Animal.Panda panda = animal.new Panda();
- System.out.println(panda.getFrom());
- System.out.println(panda.getType());
- }
- }
注意, 内部类实例化必须要先实例化外部类.
静态内部类(Static Inner Class)
静态内部类是在内部类 class 前面用 static 声明
接下来我们了解一下静态内部类的创建
- public class Animal {
- private String getType(int type) {
- if (type == 1) {
- return "birds";
- } else {
- return "mammal";
- }
- }
- static class Chicken {
- String weigth;
- public int getPrice() {
- return 1000;
- }
- }
- static class Panda {
- String gender;
- public String getFrom() {
- return "ChengDu";
- }
- }
- }
静态内部类的实例方式与非静态内部类不同, 我们来看一下
- public class Main {
- public static void main(String[] args) {
- Animal animal = new Animal();
- Animal.Chicken pig = new Animal.Chicken();
- System.out.println(pig.getPrice());
- Animal.Panda panda = new Animal.Panda();
- System.out.println(panda.getFrom());
- }
- }
注意, 与非静态内部类不同, 静态内部类不能访问外部类的成员变量以及成员方法, 因为静态内部类不需要创建外部类的实例
非静态内部类与静态内部类的异同?
静态内部类需要通过 static 修饰, 非静态内部类这不需要
非静态内部类可以访问外部类的成员变量或成员方法, 而静态内部类则不能访问
非静态内部类实例化要先实例化外部类, 而静态内部类则不需要实例化外部类
非静态内部类和静态内部类可以使用 pulic 和 protect 修饰声明
以上就是被人对 Java 中的内部类的一点理解, 如果又不对的或者不完善的, 欢迎在留言指正.
来源: https://juejin.im/post/5c3818cd6fb9a049e93cf1b8