匿名内部类学习
一个匿名内部类
package com.example.test;
public interface A {
public void eat();
}
package com.example.test;
/**
* @Author moon
* @Date 2023/4/12 11:28
* @Description TODO
*/
public class InterfaceA {
public static void main(String[] args) {
new A() {
public void eat() {
System.out.println("调用eat方法");
}
}.eat();
}
}
两个匿名内部类
package com.example.test;
public interface B {
public void eat();
public void drink();
}
package com.example.test;
/**
* @Author moon
* @Date 2023/4/12 11:31
* @Description TODO
*/
public class InterfaceB {
public static void main(String[] args) {
B b = new B() {
@Override
public void eat() {
System.out.println("eat");
}
@Override
public void drink() {
System.out.println("drink");
}
};
b.eat();
b.drink();
System.out.println(b.getClass());
}
}
不创建对象调用
package com.example.test;
public interface C {
public void eat();
}
package com.example.test;
/**
* @Author moon
* @Date 2023/4/12 11:40
* @Description TODO
*/
public class InterfaceC {
public static void main(String[] args) {
F(new C() {
@Override
public void eat() {
System.out.println("正在调用eat()");
}
});
}
public static void F(C c) {
c.eat();
}
}