1、局部内部类:
定义在外部类的局部位置,比如方法内 且有类名
public class Test {
public static void main(String[] args){
Outer outer = new Outer();
outer.f1();
}
}
/*内部类可以直接访问外部类的所有成员,包括私有的;但是外部类必须通过创建对象实例才能访问内部类成员
* 不能添加访问修饰符,因为相当于是局部变量,局部变量不能有修饰符,但可以用final修饰
* 作用域只在定义它的 方法 或是 代码块中
* 外部类和内部类重名时 遵循就近原则,如果想访问外部类,可以使用(外部类名.this.成员名)进行访问
*/
class Outer{//外部类
private int n1 = 999;
private void m2(){
System.out.println("m2方法实现");
}
public void f1(){
final class inner{//内部类(本质仍然是一个类) 可以用final修饰
public void f2(){
int n1 = 666;
System.out.println("f2方法实现");
//内部类可以直接访问外部类的所有成员,包括私有的
System.out.println(n1);//遵循就近原则 666
System.out.println(Outer.this.n1);// 外部类名.this.成员名 999
m2();
}
}
//但是外部类必须通过创建对象实例才能访问内部类成员
inner inner = new inner();
inner.f2();
}
}
2、匿名内部类:
public class Test {
public static void main(String[] args){
B b = new B();
b.f();
}
}
//是类,没有名字,同时是个对象
//new 类或接口(参数列表){类体}
interface IA{
public void cry();
}
class B {
public void f(){
// A a = new A();
// a.cry();
//基于接口的匿名内部类
IA i = new B$01(){//匿名内部类(jdk在底层创建匿名内部类,并创建实例,将地址返回给i)
//匿名内部类只能使用一次,类就消失了;但对象可多次调用 不影响
//编译类型为IA,运行类型为匿名内部类B$01
public void cry(){
System.out.println("实现cry方法");
}
};
i.cry();
}
}
class B$01 implements IA{//jdk在底层创建匿名内部类 类似于这样
public void cry(){
System.out.println("实现cry方法");
}
}
public class Test {
public static void main(String[] args){
A a = new A();
a.n1();
}
}
class A{
public void n1(){
//基于类的匿名内部类
//jdk底层:class A$01 extends F(){}
F f = new F("hsp"){
public void f1(){
System.out.println("f1方法");
}
};
f.f1();
}
}
class F{
private String name;
public F(String name){
this.name = name;
}
public void f1(){
}
}
public class Test {
public static void main(String[] args){
B b = new B();
b.b1();
}
}
abstract class A{
abstract public void a1();
}
class B {
public void b1(){
//jdk底层:class B$01 extends A{}
//编译类型A,运行类型是B$01
A a = new A(){//基于抽象类的匿名内部类
public void a1(){
System.out.println("a1");
}
};
a.a1();
}
}