最近看了一篇介绍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中的内部类的一点理解,如果又不对的或者不完善的,欢迎在留言指正。