内部类不是很好理解,但说白了其实也就是一个类中还包含着另一个类 this
如同一我的是由大脑、肢体、器官等身体结果组成,而内部类至关于其中的某个器官之一,例如心脏:它也有本身的属性和行为(血液、跳动) spa
显然,此处不能单方面用属性或者方法表示一个心脏,而须要一个类 对象
而心脏又在人体当中,正如同是内部类在外部内当中 ci
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//外部类
class Out {
private int age =12;
//内部类
class In {
public void print() {
System.out.println(age);
}
}
}
public class Demo {
public static void main(String[] args) {
Out.In in =new Out().new In();
in.print();
//或者采用下种方式访问
/*
Out out = new Out();
Out.In in = out.new In();
in.print();
*/
}
}
|
运行结果:12 it
从上面的例子不难看出,内部类其实严重破坏了良好的代码结构,但为何还要使用内部类呢? 编译
由于内部类能够随意使用外部类的成员变量(包括私有)而不用生成外部类的对象,这也是内部类的惟一优势 table
如同心脏能够直接访问身体的血液,而不是经过医生来抽血 class
程序编译事后会产生两个.class文件,分别是Out.class和Out$In.class import
其中$表明了上面程序中Out.In中的那个 . stream
Out.In in = new Out().new In()能够用来生成内部类的对象,这种方法存在两个小知识点须要注意
1.开头的Out是为了标明须要生成的内部类对象在哪一个外部类当中
2.必须先有外部类的对象才能生成内部类的对象,由于内部类的做用就是为了访问外部类中的成员变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Out {
private int age =12;
class In {
private int age =13;
public void print() {
int age =14;
System.out.println("局部变量:" + age);
System.out.println("内部类变量:" +this.age);
System.out.println("外部类变量:" + Out.this.age);
}
}
}
public class Demo {
public static void main(String[] args) {
Out.In in =new Out().new In();
in.print();
}
}
|
运行结果:
局部变量:14
内部类变量:13
外部类变量:12
从实例1中能够发现,内部类在没有同名成员变量和局部变量的状况下,内部类会直接访问外部类的成员变量,而无需指定Out.this.属性名
不然,内部类中的局部变量会覆盖外部类的成员变量
而访问内部类自己的成员变量可用this.属性名,访问外部类的成员变量须要使用Out.this.属性名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Out {
private static int age =12;
static class In {
public void print() {
System.out.println(age);
}
}
}
public class Demo {
public static void main(String[] args) {
Out.In in =new Out.In();
in.print();
}
}
|
运行结果:12
能够看到,若是用static 将内部内静态化,那么内部类就只能访问外部类的静态成员变量,具备局限性
其次,由于内部类被静态化,所以Out.In能够当作一个总体看,能够直接new 出内部类的对象(经过类名访问static,生不生成外部类对象都不要紧)