📅  最后修改于: 2020-09-26 09:13:18             🧑  作者: Mango
在Java中,没有名称的类称为匿名内部类。如果您必须重写类或接口的方法,则应使用它。 Java匿名内部类可以通过两种方式创建:
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
输出:
nice fruits
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
TestAnonymousInner$1(){}
void eat()
{
System.out.println("nice fruits");
}
}
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
输出:
nice fruits
它执行此代码后的两个主要任务:
Eatable p=new Eatable(){
void eat(){System.out.println("nice fruits");}
};
import java.io.PrintStream;
static class TestAnonymousInner1$1 implements Eatable
{
TestAnonymousInner1$1(){}
void eat(){System.out.println("nice fruits");}
}