首页 > 代码库 > 实现接口的匿名类的对象

实现接口的匿名类的对象

  1. public class TestUSB {
  2. public static void main(String[] args) {
  3. Computer c = new Computer();
  4. c.works(new USB() {//接口是没有构造器的,这里不能看作构造器,而是实现接口的匿名类
  5. @Override
  6. public void work() {
  7. System.out.println("====anonymous usb working====");
  8. }
  9. });
  10. }
  11. }
  12. class Computer {
  13. public void works(USB u) {
  14. u.work();
  15. System.out.println("====device working====");
  16. }
  17. }
  18. interface USB {
  19. void work();
  20. }
运行结果:
====anonymous usb working====
====device working====  

实现接口的匿名类的对象