Nikolas Jíša
Nikolas Jíša

Reputation: 709

Java - polymorphism with collection attributes

I would like to ask if there is a more elegant way to write the following code:

public class MTree {
    class MTreeObject {
        double[] vector;
    }

    class RoutingObject extends MTreeObject {
        double radius;
    }

    class LeafObject extends MTreeObject {
        int id;
    }

    class Node {
        LinkedList<MTreeObject> list;
    }

    class InnerNode extends Node {
        LinkedList<RoutingObject> list;
    }

    class LeafNode extends Node {
        LinkedList<LeafObject> list;
    }

    public static void main(String[] argv) {
        MTreeObject object = new RoutingObject();
        Node node = new InnerNode();
        ((InnerNode)node).list.add((RoutingObject)object);

    }
}

the problem is that if I have for example:

class Result {
    Node node;
}

and then call in main

public static void main(String[] argv) {
    Result result = new Result();
    MTreeObject object = new RoutingObject();
    result.node = new InnerNode();
    result.((InnerNode)node).list.add((RoutingObject)object);      
}

it doesn't work the way I want. Well I could also do:

newnode = result.node
((InnerNode)newnode).list.add((RoutingObject)object); 

but then I would have too much variables in my more complex code...

Upvotes: 0

Views: 162

Answers (1)

Derek Gourlay
Derek Gourlay

Reputation: 279

The problem is you have declared all your classes as inner classes of MTree. An instance of your inner classes can exist only within an instance of the outer class (MTree).

Try making your classes (RoutingObject, LeafObject, etc.) stand alone classes rather than nested or to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

MTree mtree = new MTree(); MTree.Node node = mtree.new Node();

See: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Not quite sure from your example what you are trying to accomplish, my guess best guess is you should just not use nested classes. Hope this helps.

Upvotes: 2

Related Questions