简体   繁体   中英

Creating java interface with similar methods

I'm working on simplifying code where I have two classes (Lab and Pitbull). They have the same method names but call different helper methods. The helper methods must stay.

class lab{
      void sprint(boolean start){
          Labhelper.doSomething()
      }
}
class pitbull{
      void sprint(boolean start){
          Pitbullhelper.doSomething()
      }
}

My goal is to create an interface (ie dog) where I can create a list of lab and dog but also be able to call void sprint() from that list. How might I be able to do that?

We need to create an interface Dog and Lab & Pitbull will implement this interface.

Next, we can create a list of Dog which can contain instances of both Lab and Pitbull. When this list is iterated over and sprint method is called, the implementation will get invoked based on the object calling it.

See below code -

interface Dog {
    void sprint(boolean start);
}

class Lab implements Dog {
  @Override
  public void sprint(boolean start) {
    Labhelper.doSomething();    
  }
}

class Pitbull implements Dog {
  @Override
  public void sprint(boolean start) {
    Pitbullhelper.doSomething();
  }
}

public class MainClass {
  public static void main(String[] args) {
    List<Dog> dogs = new ArrayList<>();
    dogs.add(new Lab());
    dogs.add(new Pitbull());
    dogs.forEach(dog -> dog.sprint(true));
  }
}

In above code, when sprint() is called on first object, implementation of Lab class will be invoked while for second object implemenattion of Pitbull class will be invoked.

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