原文链接: 点击打开链接
1. 匿名类需要继承一个方法或接口
不使用匿名内部类来实现抽象类
abstract class Person{
public abstract void eat();
}
class Child extends Person{
public void eat(){
System.out.println("eat something");
}
}
public class Ordinary {
public static void main(String[] args) {
Person p = new Child();
p.eat();
}
}
2. 匿名内部类的基本实现
abstract class Person{
public abstract void eat();
}
public class Ordinary {
public static void main(String[] args) {
Person p = new Person(){
public void eat(){
System.out.println("eat something");
}
};
p.eat();
}
}
3. 在接口上使用匿名内部类
interface Person{
public abstract void eat();
}
public class Ordinary {
public static void main(String[] args) {
Person p = new Person(){
public void eat(){
System.out.println("eat something");
}
};
p.eat();
}
}
本文详细介绍了在Java中使用匿名类和接口的基本实现方式,包括如何继承抽象类的方法,如何在接口上使用匿名内部类,以及具体代码示例。
2747

被折叠的 条评论
为什么被折叠?



