day11--匿名内部类的概念与使用

This commit is contained in:
xx
2026-10-09 15:23:24 +08:00
parent bc610b6d32
commit d3838a1c9e
2 changed files with 50 additions and 0 deletions
@@ -0,0 +1,45 @@
package com.inmind.noname_innercalss04;
/*
匿名内部类:定义在类中的一个没有名字的类
我们在使用接口时,能否不定义实现类,就直接创建出对应的接口的实现类对象
匿名内部类 :是内部类的简化写法。它的本质是一个带具体实现的 父类或者父接口的 匿名的 子类对象。
匿名内部类的定义:
{
String name;
@Override
public void method() {
System.out.println("匿名内部类的method方法执行了");
}
};
*/
public class Demo07 {
public static void main(String[] args) {
/*//1.普通的接口实现类的使用
MyInterfaceImpl impl = new MyInterfaceImpl();
impl.method();
//2.多态:父类引用指向子类对象
MyInterface impl1 = new MyInterfaceImpl();
impl1.method();*/
/*
当我们只需要定义出一个接口或者父类的子类,并且该子类只需要使用一次时,
能不能省略掉MyInterfaceImpl实现类的定义,直接使用接口或父类的匿名内部类
当前就是匿名内部类的定义和对象的创建过程
*/
//3.接口的匿名内部类的写法:
MyInterface impl2 = new MyInterface(){
@Override
public void method() {
System.out.println("匿名内部类的method方法");
}
};
impl2.method();
//4.抽象父类的匿名内部类写法
//5.普通父类的匿名内部类写法
}
}
@@ -0,0 +1,5 @@
package com.inmind.noname_innercalss04;
public interface MyInterface {
void method();
}