Reputation: 51
When I try to compile my derived class IntSearchTree, the error message
IntSearchTree.java:3: error: constructor IntBinTree in class IntBinTree
cannot be applied to given types;
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
required: int,IntBinTree,IntBinTree
found: no arguments
reason: actual and formal argument lists differ in length
1 error
, appears.
The following code shows the most important lines of the base class:
class IntBinTree {
int node;
IntBinTree left;
IntBinTree right;
IntBinTree(int node, IntBinTree left, IntBinTree right) {
this.node = node;
this.left = left;
this.right = right;
}
}
And the most important lines of the derived class:
class IntSearchTree extends IntBinTree {
IntSearchTree left;
IntSearchTree right;
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
this.node = node;
this.left = left;
this.right = right;
}
}
I tried to solve that problem by giving the constructor in the base clase the private modifier
private IntBinTree(int node, IntBinTree left, IntBinTree right) {...}
, but the compiling error message was the same.
So the first question is how is it possible to define a constructor in a way that it is visible in the base class, but not in derived classes?
And the second question is, why is the base constructor still visible in the derived class, even if I use the private modifier?
Upvotes: 1
Views: 71
Reputation: 11
I can see two problems with that implementation.
super(node, left, right)
in your current constructor, or super()
. Remember that java creates by default public parameterless constructor for any class you create.Upvotes: 1
Reputation: 4667
You need a no-args constructor.
Place this into your IntBinTree class:
IntBinTree()
{
}
Or you can use this instead in the IntSearchTree class:
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
super(node,left,right);
}
When you do not have a no-args constructor in the super class, you need to explicitly call the constructor you want to use in the child class. This super() will call the constructor that takes in the node, left, right
from IntBinTree()
.
Upvotes: 1