创建具有类似方法的Java接口。

huangapple go评论55阅读模式
英文:

Creating java interface with similar methods

问题

我正在简化代码,其中我有两个类(Lab和Pitbull)。它们具有相同的方法名称,但调用不同的辅助方法。这些辅助方法必须保持不变。

我的目标是创建一个接口(即dog),在这个接口中,我可以创建一个Lab和Pitbull的列表,同时还可以从该列表调用void sprint()。我应该如何实现这个目标呢?

英文:

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

得分: 3

我们需要创建一个接口Dog,Lab和Pitbull将实现这个接口。

接下来,我们可以创建一个Dog的列表,其中可以包含Lab和Pitbull的实例。当遍历此列表并调用sprint方法时,将根据调用它的对象来调用实现。

请参阅下面的代码 -

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

在上述代码中,当在第一个对象上调用sprint()时,将调用Lab类的实现,而对于第二个对象,将调用Pitbull类的实现。

英文:

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&lt;Dog&gt; dogs = new ArrayList&lt;&gt;();
	dogs.add(new Lab());
	dogs.add(new Pitbull());
	dogs.forEach(dog -&gt; 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.

huangapple
  • 本文由 发表于 2020年9月17日 13:56:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63932054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定