I have a superclass and a subclass as follows:
class Tree{
..
public void add(..){
//makes a call to protected function add(..)
}//for client to use.
protected TreeNode add(..){}//recursive function which calls itslef
}
class Stree extends Tree{
//overrides the recursive add function from class Tree
protected TreeNode add(..){
..
super.add();//calls the non-recursive add function in superclass.
}
}
The problem here is that when I call super.add()
from the new add function in the subclass, it goes to Tree.add()
. Inside Tree.add()
. there is a call to add()
, which calls the recursive add function in the subclass instead of super, i.e. Stree.add()
, instead of Tree.add()
which results in an infinite loop. Do you guys see where the problem is?
This is a homework assignment hence I cannot change the name of the recursive function. I am explicitly required to add functionality to the recursive add function, without rewriting any existing code, which basically means I will have to make a call to the original add()
function.
edit: Code for the Tree.add()//recursive. Note that I cannot modify this code to gain the functionality I seek.
protected StreeNode add(StreeNode node, String value) {
if (node == null) {
node = new StreeNode(value);
numElements++;
} else if (node.data.compareTo(value) == 0) {
// do nothing, String was already in Set
} else if (node.data.compareTo(value) > 0) {
node.left = add(node.left, value); // x = change(x)
} else {
node.right = add(node.right, value); // x = change(x)
}
return node;
}
edit: Now that I see that this is the expected behaviour, how do I go about achieving the following:
- Add the value using the original recursive
add()
- Implement extra functionality