开发者

Is it possible to use inheritance in this situation? (Java)

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 in开发者_开发技巧sertion to use NodeB.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜