views:

75

answers:

2

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?

+1  A: 

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.

Alex Martelli
+1  A: 

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.

Steven Schlansker