【问题标题】:How to force an implementing class to inherit from one or another subclass?如何强制实现类从一个或另一个子类继承?
【发布时间】:2011-03-17 15:59:52
【问题描述】:

我有一个抽象类MotherClass 和两个抽象类ChildClass1ChildClass2 扩展MotherClass

我希望确保任何扩展MotherClass 的类实际上都会扩展ChildClass1ChildClass2。我觉得我的基于树的类设计有问题。你知道如何正确地制作它吗?

【问题讨论】:

  • MotherClass 可以保密吗?
  • 为什么要强制这样做?
  • @Mark 因为我的MotherClass 没有“输入”到足以使用;从该类派生的实例需要通过ChildClass1ChildClass2 实现更多功能。
  • 我明白,但这与任何抽象类有什么不同?只要满足可替代性原则,扩展MotherClass 的人有什么阴险之处?你为什么要保护自己免受其他开发人员的伤害?这是倒退:您应该公开泛型类型并隐藏实现类。
  • @Mark 同意,这有点乱。谢谢您的回答 !我不会实施它们,但我学到了一些东西 - 最终网站的全部目的似乎。

标签: java class inheritance


【解决方案1】:

如果MotherClass 具有包可见性并且ChildClass1ChildClass2 是公共的并且在同一个包中,则您可以将这两个子类化,但不能将MotherClass 子类化。

编辑:

另一种可能性:

interface Marker {} //note that this is package private

public abstract class Mother<T extends Marker > {}

public class ChildA extends Mother<ChildA> implements Marker {}

public class ChildB extends Mother<ChildB> implements Marker {}

方法:

doSomething(Mother<?> mother() {}

你现在做不到

class GrandChild extends Mother<GrandChild> {}

这会编译,但至少会给你一个警告:

class GrandChild extends Mother {} //warning like "Mother is a raw type"

没有警告的方式:

class GrandChild extends ChildA {} 
class GrandChild extends ChildB {} 

【讨论】:

  • 5 秒前有这个想法 =) (+1)
  • 我仍然需要让它们的公共根可见。并非所有功能都特定于 Child 子类,因此我需要能够在某些方法中将一个或另一个类作为 MotherClass 传递。
  • 然后使用一个用于参数的通用接口,由MotherClass实现。除此之外,您需要像 Joachim Sauer 建议的那样检查 instanceof
【解决方案2】:

把这个放到MotherClass的构造函数中:

protected MotherClass() {
  if (!(this instanceof ChildClass1 || this instanceof ChildClass2)) {
    throw new IllegalStateException("Oh noes!");
  }
}

这个(诚然丑陋的)解决方案受到 SWT 的启发,它的 Widget 类中有这样的代码:

protected void checkSubclass () {
    if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS);
}

checkSubclassWidget 的唯一构造函数中被调用。

这样做是为了避免对 SWT 小部件类进行子类化(因为不受支持且不应这样做)。请注意,checkSubsclass() 不是 final。因此,如果您真的想要扩展 Button(并准备承受后果),您可以将 checkSubclass() 覆盖为无操作方法。

【讨论】:

  • 明天他会得到 ChildClass3 和 ChildClass4 忘记修改构造函数...
  • 谢谢 :) 但这会在运行时出错,而不是在编译时出错。我想在编译时确保这种奇怪的行为。
  • @Mark:同意,但在我看来,这已经在要求中了。
  • 是的,我试图说服他他的要求也被打破了:-)。
【解决方案3】:

ChildClass1ChildClass2 中提取通用功能并将其移至MotherClass 或派生自MotherClass 的其他抽象类。

【讨论】:

  • 关键是如果你想强制两个类的继承,那么它们有一些共同点,可以向上移动。如果不是,那么您不需要此类限制。
  • 你没听懂我的意思。我希望一个类扩展一个或另一个子类 - 不是两个!
猜你喜欢
  • 2013-08-12
  • 2014-11-22
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
相关资源
最近更新 更多