Home > Net >  Why is the superclasses field different when called from subclass?
Why is the superclasses field different when called from subclass?

Time:05-18

Why is field nodes returning different size when called from subclass

shouldn't subclasses have access to their super classes fields?

Here is reproducible example:

Manager.java

import java.util.HashMap;

public class Manager {
    protected HashMap<Integer,Node> nodes = new HashMap<>();

    public HashMap<Integer, Node> getNodes() { return nodes; }

    public void addNode(Node node){
        nodes.put(nodes.size(),node);
    }

    public static void main(String[] args) {
        Manager manager = new Manager();
        manager.addNode(new Node());
        System.out.println("(from Manager) manager.nodes.size() = "   manager.nodes.size());
        manager.getNodes().get(0).printNodesSize();
    }
}

Node.java

public class Node extends Manager {
    public void printNodesSize() {
        System.out.println("(from Node) manager.nodes.size() = "   super.nodes.size());
    }
}

System.out:

(from Manager) manager.nodes.size() = 1
(from instanced Node) manager.nodes.size() = 0

Process finished with exit code 0

CodePudding user response:

The issue you're having has nothing to see with inheritance. The call:

manager.getNodes()

will return a Map<Integer, Node> (check your own method definition in the class Manager) that contains only one element with index 1 (because it's you defining the key as nodes.size() 1).

Hence when you call manager.getNodes().get(0), you get a null element (the map doesn't contain any element with key 0).

If you replace .get(0) by .get(1), it will work.

Side note: your design is not very clean. The class Manager (parent) contains a map of Nodes which is its own child. The child (Node) is supposed to know its parent (Manager), but not vice versa.

Edit

The print of super.nodes.size() is 0 because you're not pointing to the instance of Manager that you think you're pointing to.

When you do new Node() (the node that you add to your manager), you're creating a new Manager() which has an empty map by default.

So when you call super.nodes.size(), your super is not manager as you think, but the other instance of Manager that you created when doing new Node(), to which you never added anything.

Again, I suggest you check my side-note above and re-consider your design.

  • Related