匿名内部类
本质是一个继承了该类或实现了该接口的子类匿名对象
注意:只要一个类是抽象的或者一个接口,那么其子类中的方法都可以使用匿名内部类来实现。
最常用的情况就是在多线程的实现上,因为要实现多线程必须继承Thread类或者继承Runnable接口
- 实例1: 不使用匿名内部类来实现抽象方法
abstract class Person {
public abstract void eat();
}
class Child extends Person {
public void eat() {
System.out.println("Child eat sth");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Child();
p.eat();
}
}
可以看到,我们使用Child继承Person类,然后实现了Child的一个实例,将其向上转型为Persion类的引用,但是如果此处的Child类只使用一次,那么将其编写为独立的一个类岂不是很麻烦?
这个时候就引入了匿名内部类
- 实例2: 使用匿名内部类来实现抽象方法
abstract class Person {
public abstract void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person() {
public void eat() {
System.out.println("eat sth");
}
};
p.eat();
}
}
可以看到,我们直接将抽象类Person中的方法在大括号中实现了,这样便可以省略一个类的书写。
- 实例3:接口的匿名内部类实现,接口使用匿名内部类的情况和格式也是一样的。
interface Person {
public void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person() {
public void eat() {
System.out.println("eat sth");
}
};
p.eat();
}
}
- 实例4:Thread类的匿名内部类实现
public class Demo1 {
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
System.out.println("Thread ");
}
};
t.start();
}
}
- 实例5:Runnable接口的匿名内部类实现
public class Demo1 {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Runnable");
}
};
Thread t=new Thread(r);
t.start();
}
}