简体   繁体   中英

Call different methods from different classes in a single reference in java

Having issue in Java, we can call class methods like

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();

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM