[英]Call different methods from different classes in a single reference in java
Having issue in Java, we can call class methods like 在Java中遇到问题时,我们可以调用类似
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
samp s= new ClassB();
s.printMsg();
}
}
we can do this, am having different type of class method not similar methods for all classes but I want to implement the future is it possible to do? 我们可以做到这一点,是否有不同类型的类方法,而不是所有类都具有相似的方法,但是我想实现将来的可能吗? is any other pattern for this, pls help me to find this. 还有其他模式吗,请帮助我找到这个。 like 喜欢
ClassA{
public void fun1(){..}
public void fun2(){..}
}
ClassB{
public void fun3(){..}
public void fun4(){..}
}
want to call these methods using a single refrence, need to asign object to that refrence dynamically is it possible friends?... Thanks in advance 想要使用单个引用调用这些方法,需要动态地将对象分配给该引用,这是否可能是朋友?...在此先感谢
您不能使用通用接口来做到这一点。您只能使用接口引用类型调用在接口中定义的方法,即使它所指向的对象属于另一个类也具有不同的其他方法。
you can call only those class function which are defined in interface because its reference can access only those functions. 您只能调用接口中定义的类函数,因为其引用只能访问那些函数。 ex: 例如:
interface samp{
public void printMsg();
}
ClassA implements samp{
public void printMsg()
{
S.o.p("Hi ClassA");
}
public void newmthd(){
S.o.p("you can't call me from samp reference.");
}
}
ClassB implements samp{
public void printMsg()
{
S.o.p("Hi ClassB");
}
}
public MainClass{
public static void main(String args())
{
samp s= new ClassA();
s.printMsg();
s.newmthd() //error... s don't have any knowledge of this function.
samp s= new ClassB();
s.printMsg();
}
} }
Define all the methods you want your reference to have in an a superclass, but leave the implementations empty. 在超类中定义您希望引用拥有的所有方法,但是将实现留空。 Then, create your subclass and override the necessary methods. 然后,创建您的子类并覆盖必要的方法。
Example: 例:
Class MySuperClass {
public void fun1() {}
public void fun2() {}
public void fun3() {}
public void fun4() {}
}
Class ClassA extends MySuperClass {
public void fun1() { //implementation details }
public void fun2() { //implementation details }
}
Class ClassB extends MySuperClass {
public void fun3() { //implementation details }
public void fun4() { //implementation details }
}
public Class Tester {
public static void main(String[] args) {
MySuperClass class1 = new ClassA();
MySuperClass class2 = new ClassB();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.