超越时使用组合继承 [英] Using composition over inheritance when overriding

查看:120
本文介绍了超越时使用组合继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类,我想通过覆盖一个如果它的方法唯一我可以做的是通过使用继承(子类和覆盖方法)自定义的类?是否可以以某种方式使用组合来实现同样的目标?

解决方案

是的,您可以使用委派。 Bar 包含一个 Foo Foo $ c>并代表它选择它。

  interface SomeMethods {
void doSomething();
void doSomethingElse();
}

class Foo实现SomeMethod {
public void doSomething(){// implementation}
public void doSomethingElse(){// implementation}
}

class Bar implements SomeMethod {
private final Foo foo = new Foo();

public void doSomething(){foo.doSomething(); }
public void doSomethingElse(){//做别的事情! }
}


If I have a class that I would like to customise by overriding one if its methods the only I can do this is by using inheritance (sub-classing and overriding method) ? Is it possible to use composition in some way to achieve same goal ?

解决方案

Yes, you can use delegation. Instead of deriving from Foo in the example below, Bar contains a Foo and delegates to it where it chooses.

interface SomeMethods {
  void doSomething();
  void doSomethingElse();
}

class Foo implements SomeMethod {
  public void doSomething() { // implementation }
  public void doSomethingElse() { // implementation }
}

class Bar implements SomeMethod {
   private final Foo foo = new Foo();

   public void doSomething() { foo.doSomething(); }
   public void doSomethingElse() { // do something else! }
}

这篇关于超越时使用组合继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆