在这种情况下可以使用继承吗? (爪哇)

发布于 2024-09-01 06:04:32 字数 273 浏览 4 评论 0原文

我有 ClassA 和 ClassB,其中 ClassA 是超类。

ClassA 使用 NodeA,ClassB 使用 NodeB。

第一个问题:方法参数。 ClassB 需要 NodeB 类型,但我无法从子类转换为超类。这意味着我无法设置 NodeB 特有的属性。

第二个问题:当我需要向ClassB添加节点时,我必须实例化一个新的NodeB。但是,我无法在超类中执行此操作,因此我必须重写插入以使用 NodeB。

有没有办法解决这个问题,或者我必须重写整个事情?

I have ClassA and ClassB, with ClassA being the superclass.

ClassA uses NodeA, ClassB uses NodeB.

First problem: method parameters. ClassB needs NodeB types, but I can't cast from the subclass to the superclass. That means I can't set properties which are unique to NodeB's.

Second problem: When I need to add nodes toClassB, I have to instantiate a new NodeB. But, I can't do this in the superclass, so I'd have to rewrite the insertion to use NodeB.

Is there a way around it or am I gonna have to rewrite the whole thing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘落散花 2024-09-08 06:04:32

我认为,解决您的困境的最佳解决方案是使用泛型:将公共代码放入一个(可能是抽象的)公共超类中,该超类由 NodeType 参数化。 A 和 B 中的每一个都可以分别子类化 CommonSuperCommonSuper,并在需要执行特定于其各自节点类型的操作时进行重写。这样,您的代码中就会很少有重复,但仍能够完成您需要的所有工作。

Best solution to your quandary, I think, is to use generics: put the common code in a (possibly abstract) common superclass parameterized by, say, NodeType. Each of A and B can subclass respectively CommonSuper<NodeA> and CommonSuper<NodeB>, and override where needed to do something specific to their individual node type. This way, you'll have very little duplication in your code, yet be able to accomplish all you need to.

年少掌心 2024-09-08 06:04:32

也许您正在寻找这样的东西?

class NodeA { ... }
class NodeB extends NodeA { ... }

class ClassA<N extends NodeA> {
    public Node newNode() { return new NodeA(); }
    public void setProperties(Node n) { setPropertiesA(n); }
}

class ClassB extends ClassA<NodeB> {
    @Override
    public NodeB newNode() { return new NodeB(); }
    @Override
    public void setProperties(NodeB n) { setPropertiesB(n); super.setProperties(n); }
}

这就是你所要求的吗?

特别要注意 ClassB 如何重写 addNode 以返回子类,以及“链接”setProperties 以在适当时设置 NodeB 的属性。

Perhaps you're looking for something like this?

class NodeA { ... }
class NodeB extends NodeA { ... }

class ClassA<N extends NodeA> {
    public Node newNode() { return new NodeA(); }
    public void setProperties(Node n) { setPropertiesA(n); }
}

class ClassB extends ClassA<NodeB> {
    @Override
    public NodeB newNode() { return new NodeB(); }
    @Override
    public void setProperties(NodeB n) { setPropertiesB(n); super.setProperties(n); }
}

Is that what you're asking for, roughly?

In particular, note how ClassB overrides addNode to return the subclass, and the setProperties are "chained" to set the properties of NodeB when appropriate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文