1、实现抽象类的抽象方法
abstract class Person{
abstract public void eat();
}
class Child extends Person{
@Override
public void eat() {
System.out.println("child eat");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Person(){
@Override
public void eat() {
System.out.println("child eat");
}
};
p.eat();
}
}
打印:child eat,效果等于Person p = new Child();p.eat();
2、实现接口里面的方法
interface Person{
abstract public void eat();
}
class Child implements Person{
@Override
public void eat() {
System.out.println("child eat");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Person(){
@Override
public void eat() {
System.out.println("child eat");
}
};
p.eat();
}
}
打印:child eat
俩个实例:
public class Demo {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println("child eat");
}
};
t.start();
}
}
public class Demo {
public static void main(String[] args) {
Runnable r = new Runnable(){
@Override
public void run() {
System.out.println("child eat");
}
};
new Thread(r).start();
}
}