Search code examples
javabinary-treebinary-search-treeinstance-variablesprotected

How can I call a protected variable in a subclass method in an equals function?


It is a pretty simple equals method.

Here's what I have in my code:

public boolean equals(Object other) 
      if (other == null) {
                return false;
            }
            if (!(other instanceof BinaryTree)) {
                return false;
            }
            return this.equalsUtil(this.root, other.root);
        }

Here's the initial problem

public class BinaryTree {
    protected class Node {
        //instancee variables and a constructor
    }
    protected Node root;
    //remainder ommited for brevity

I can't call other.root (Object other being the parameter for equals), how can I do this then?

Note that my class is public class MyBinaryTree extends Bina


Solution

  • The variable being protected has nothing to do with this. You just have to cast other to BinaryTree, e.g. BinaryTree o = (BinaryTree) other; return this.equalsUtil(this.root, o.root);