0

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 (i.e 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?

1
  • 5
    Show us your attempt to create the said dog interface. Commented Sep 17, 2020 at 5:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.