总结:
接口被实现时,方法必须被声明为public。
package pkg;
//--- service ----
interface Service{
void method1();
void method2();
}
class imp1 implements Service{
imp1(){
System.out.println("imp 1 constructing");
}
public void method1(){System.out.println("imp 1.method 1");}
public void method2(){System.out.println("imp 1.method2");}
}
class imp2 implements Service{
imp2(){
System.out.println("imp 2 constructing");
}
public void method1(){System.out.println("imp 2.method 1");}
public void method2(){System.out.println("imp 2.method2");}
}
//--- factory ---
interface ServiceFactory{
Service getService();//connecting factory and service
}
class impfactory1 implements ServiceFactory{
public Service getService(){return new imp1();};//also can be imp2:UPCAST
}
class impfactory2 implements ServiceFactory{
public imp2 getService(){return new imp2();};//also can be Service
}
// main
public class p187{
public static void ServiceConsume(ServiceFactory fact){
Service s=fact.getService();//UPCAST in different place:here OR impfactoryN
s.method1();
s.method2();
}
public static void main(String[] args){
ServiceConsume(new impfactory1());
ServiceConsume(new impfactory2());
}
}
output:
imp 1 constructing
imp 1.method 1
imp 1.method2
imp 2 constructing
imp 2.method 1
imp 2.method2