在这种情况下可以使用继承吗? (爪哇)
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为,解决您的困境的最佳解决方案是使用泛型:将公共代码放入一个(可能是抽象的)公共超类中,该超类由
NodeType
参数化。 A 和 B 中的每一个都可以分别子类化CommonSuper
和CommonSuper
,并在需要执行特定于其各自节点类型的操作时进行重写。这样,您的代码中就会很少有重复,但仍能够完成您需要的所有工作。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 respectivelyCommonSuper<NodeA>
andCommonSuper<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.也许您正在寻找这样的东西?
这就是你所要求的吗?
特别要注意 ClassB 如何重写 addNode 以返回子类,以及“链接”setProperties 以在适当时设置 NodeB 的属性。
Perhaps you're looking for something like this?
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.