Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 编译派生类时出现错误消息_Java_Inheritance_Constructor - Fatal编程技术网

Java 编译派生类时出现错误消息

Java 编译派生类时出现错误消息,java,inheritance,constructor,Java,Inheritance,Constructor,当我试图编译我的派生类IntSearchTree时,错误消息 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:

当我试图编译我的派生类IntSearchTree时,错误消息

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
,出现

以下代码显示了基类中最重要的行:

 class IntBinTree {
   int node;
   IntBinTree left;
   IntBinTree right;

   IntBinTree(int node, IntBinTree left, IntBinTree right) {
     this.node = node;
     this.left = left;
     this.right = right;
   }
 }
以及派生类中最重要的行:

 class IntSearchTree extends IntBinTree {
 IntSearchTree left;
 IntSearchTree right;

   IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
     this.node = node;
     this.left = left;
     this.right = right;
   }
 }
我试图通过给基类中的构造函数私有修饰符来解决这个问题

 private IntBinTree(int node, IntBinTree left, IntBinTree right) {...}
,但编译错误消息是相同的

所以第一个问题是,如何定义一个构造函数,使它在基类中可见,而在派生类中不可见


第二个问题是,为什么即使我使用私有修饰符,基构造函数在派生类中仍然可见?

您需要一个无参数构造函数

将其放入IntBinTree类:

IntBinTree()
{
}
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
     super(node,left,right);
  }
也可以在IntSearchTree类中使用此选项:

IntBinTree()
{
}
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
     super(node,left,right);
  }

如果在超类中没有无参数构造函数,则需要显式调用要在子类中使用的构造函数。这个super()将调用从
IntBinTree()

中获取左、右
节点的构造函数。我发现该实现存在两个问题

  • 您可能不想在派生类中再次声明leftright字段-这不会导致编译错误,但肯定会导致以后难以调试的一些问题
  • 创建派生类需要调用其超类的构造函数-在这种情况下,您可以在当前构造函数中调用
    super(node,left,right)
    ,或
    super()
    。请记住,java默认为您创建的任何类创建公共无参数构造函数

  • 谢谢,两个建议都很有效。因此,没有办法使基类的所有构造函数在派生类中不可见,对吗?您需要了解Java中的“构造函数链接”。