一. 成员内部类
在类的成员位置 , 定义的内部类 。
在使用时 , 类中将其看做一个成员
1.1) outer 中的私有成员 inner 中能使用
inner 中的私有成员 outer 中也能使用1.2) 一般情况下, inner 的对象只会在 outer 中使用
1.3) 如果 inner 中有属性和 outer 重名
this.<属性>-----inner 的属性
<outer类名>.this.<属性>-------outer 的属性
1.4) 任何内部类都会有自己独立的 class 文件
1.5) 实际上 inner 可以在其他类中实例化但是了解即可
代码块:
主类 InnerDemo.java
public class InnerDemo {
public static void main(String[] args) {
Aoo.Boo aoo = new Aoo().new Boo();
}
}
子类 Aoo 和 Boo
class Aoo {
private int a;
int b;
//成员内部类
class Boo {
int b;
private int c;
int d;
public void method01() {
Aoo.this.a = 1;//Aoo.a
this.b = 2;//Boo.b
Aoo.this.b = 12;//Aoo.b
c = 4;
d = 5;
}
}
public void method02() {
Boo boo = new Boo();
boo.c = 10;
boo.d = 15;
}
}
二. 匿名内部类
匿名内部类是一种特殊的内部类
匿名内部类是一种特殊的内部类
2.1) 匿名内部类没有特定的类名
2.2) 匿名内部类编写在一个方法中
2.3) 匿名内部类必须选择一个类或接口继承
2.4) 语法
<父类名> <引用> = new <父类名> ( ) {
//匿名内部类内容
} ;
2.5) 匿名内部类中
只能对方法中的局部变量访问
但是不能修改
jdk1.6 之前
要求匿名内部类中使用的局部变量
必须用 final 修饰
代码块:
主类 AnonymousInnerDemo.java
public class AnonymousInnerDemo {
public static void main(String[] args) {
Person p = new Person() {
String name = "二毛";
int age = 18;
@Override
public void eat() {
System.out.println("我是小哥哥, 名字叫: " +this.name +", 年龄是: " +this.age);
}
};
p.eat();
}
}
abstract class Person{
public abstract void eat();
}
Print Result:
我是小哥哥, 名字叫: 二毛, 年龄是: 18