首页 > 代码库 > Java-- 匿名类
Java-- 匿名类
工厂方法
匿名类与正规的继承相比有些受限,因为匿名类既可以扩展类,也可以实现接口,但不能两者兼备。如果实现接口,也就只能实现一个接口。
1 package innerclasses; 2 3 4 interface Service{ 5 void method1(); 6 void method2(); 7 } 8 9 interface ServiceFactory{10 Service getService();11 }12 13 class Implementation1 implements Service{14 private Implementation1(){}15 public void method1(){16 System.out.println("Implemention1 method1");17 }18 public void method2(){19 System.out.println("Implemention1 method1");20 }21 //下面是匿名类22 public static ServiceFactory factory = new ServiceFactory(){23 public Service getService(){24 return new Implementation1();25 }26 };27 }28 29 class Implementation2 implements Service{30 private Implementation2(){}31 public void method1(){32 System.out.println("Implemention2 method1");33 }34 public void method2(){35 System.out.println("Implemention2 method2");36 }37 38 public static ServiceFactory factory = new ServiceFactory(){39 public Service getService(){40 return new Implementation2();41 }42 };43 }44 45 public class Factories{46 public static void serviceConsumer(ServiceFactory fact){47 Service s = fact.getService();48 s.method1();49 s.method2();50 }51 public static void main(String [] args){52 serviceConsumer(Implementation1.factory);53 serviceConsumer(Implementation2.factory);54 }55 }
结果:
Implemention1 method1Implemention1 method1Implemention2 method1Implemention2 method2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。