Question

I've been looking at this problem for a while, and I can't figure out a solution to it.

private abstract class Node {
    private Rectangle bounds;
}
private class LeafNode extends Node {
    private Rectangle bounds;
    ....    
}

private class InternalNode extends Node{
    private Rectangle bounds;
    ....
} 

So I'm getting a null pointer error so I went through the debugger in eclipse. But what's confusing me is in eclipse, it's showing that there are two bounds fields, and I'm pretty sure I'm accessing the null one, instead of the one I actually set.

enter image description here

When I'm in the debugger, sometimes I see the first bounds variable being used, and other times I see the second one being used. The only possible thing I could think of is that throughout the code, I do some casting with LeafNode and InternalNode. So could the two bounds variables be linked with the abstract class I'm using?

Was it helpful?

Solution

Take a look in topics related to Field Shadowing.

In brief, there is no "overriding" for member variable in Java. If you declare a member variable with the same name in your child class as your parent, the child member variable is "shadowing" the parent's.

Use your code as an example, in a LeafNode instance, there are actually two member variables called bounds, which you can think of as "Node::bounds" and "LeafNode::bounds".

if you are accessing through a Node reference, you are going to interact with Node::bounds, and LeafNode::bounds if through an NodeLeaf reference.

e.g.

LeafNode leafNode = new LeafNode();
Node node = leafNode;

leafNode.bounds = xxx;  // accessing LeafNode::bounds
node.bounds = yyy; // accessing Node::bounds

In your case, I don't see any reason for keeping a separate bounds in child class. Consider changing Node::bounds to be protected and use that in your child class instead.

OTHER TIPS

In Java, fields declared in a subclass "shadow" but do not override fields bound in a superclass like methods do. Fields declared in the subclass exist separately from those in the superclass; you can access the superclass' fields via super.field (or by ((Ancestor) this).field for more distant superclasses).

So, the two bounds that you see are really different bounds's - one from InternalNode and one from Node. From what I can tell, it's probably best in your case for you to remove the bounds declarations from LeafNode and InternalNode entirely, leaving it only in the Node class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top