简体   繁体   中英

How to call methods of different classes passed as parameter type?

How would I do something like this? Ignore the syntax errors.

//some class
class A {
    //some func
    func(){
    
    }
}

class B {
    func2(){
    }
}

//Generic Class that can take type A or B
class generic<T> {
    func3(T){
        //How to do this?
        T.func();
        T.func2();
    }
}

I really don't understand Generics. Sorry if it sounds ridiculous.

You use generic to abstract the "shape" of class you can work on without caring about the actual implementation classes.

You should create a common interface

interface Common {
  void doWork();
}

//some class
class A implements Common {
    void doWork() {
      func();
    }

    //some func
    func(){
    
    }
}

class B implements Common {
    void doWork() {
      func2();
    }

    func2(){
    }
}

//Generic Class that can take type A or B
class generic<T extends Common> {
    func3(T task){
        task.doWork();
    }
}

So pretty much you want to have a class that takes another Util class(or whatever it does) And calls some standard(generic) method on it. What i would do is Create an interface with the method;

public interface ExampleInterface {
   void methodToCall();
}

Then you have your class that takes a implementation of that Interface;

public class OtherExampleClass<T extends ExampleInterface> {
    public void call(T caller){
       caller.methodToCall();
    }
}

For the record, So far this really doesnt need to be genericized at all, I would really only do this if your Class 'A' and 'B' have some specific return type based on which one you provide when instantiated your 'Generic' class.

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