gpt4 book ai didi

java - 为什么我需要在这里明确地写一个构造函数?

转载 作者:行者123 更新时间:2023-12-03 21:44:51 25 4
gpt4 key购买 nike

这就是我遇到的问题。我举个例子:

package check;

public class Check {
int a,b;
Check (int i,int j) {
a = i;
b = j;
}
}

这很好。现在我想通过扩展 Check 创建一个子类。所以我写道:

class V extends Check {

}

我刚写完,Eclipse中就出现了一个叉号,点开发现一条消息:

implicit super constructor Check() is undefined for default constructor. Must define an explicit constructor.

我用谷歌搜索了这个问题并添加了

V (int i, int j) {
super(i, j);
}

Eclipse 也在暗示它。现在我有两个问题。

  1. 为什么必须为 class V 使用构造函数? AFAIK,创建构造函数不是必需的,因为 JAVA 编译器会自动创建默认构造函数来执行其操作。另外从消息来看,似乎还需要一个默认构造函数,但不是我写的,但正如我所说,JAVA 不会自动创建它吗?
  2. 另一件事,我将子类中的代码更改为 V(int i, int j){ super.a=i; super.b=j}.,但我仍然遇到错误。这是为什么?这段代码是不是 super.a=i; super.b=jsuper(i,j) 一样吗?另外,在V类中,我可能不需要使用b,那我为什么要用构造函数初始化它呢?

最佳答案

1) Why is it compulsory to use a constructor at all for class V? AFAIK, creating a constructor is not necessary as JAVA compiler creates default constructor automatically to carry on its operation. Also from the message, it also seems a default constructor is needed, but is not written by me, but as I said doesn't JAVA create it automatically?

仅当不存在其他构造函数时才会创建默认构造函数,当您创建构造函数时 Check(int i,int j) 您删除了默认构造函数。

当您不在构造函数中包含对 super 的调用时,java 默认会尝试调用 super()。但是,由于父类中没有默认构造函数,因此无法执行此操作。

这种行为很好,因为您可能不需要默认构造函数;某些变量可能必须被初始化以使对象正确运行。因此,需要有一种方法来删除默认构造函数,这是通过显式创建构造函数来完成的。

2) Another thing, I changed the code in subclass as V(int i, int j){ super.a=i; super.b=j}., but I was still getting error. Why is that? Isn't this code super.a=i; super.b=j same with super(i,j)? Also, in class V, I might not need to use b, then why should I need to initialize it by a constructor?

代码

V(int i, int j){ 
super.a=i; super.b=j
}

仍然没有调用父构造函数,这样就变成了

V(int i, int j){ 
super();
super.a=i; super.b=j
}

而且 super() 也不存在

必须存在对 super 的一些调用以“设置”对象的父部分,一直向下到 Object(所有对象都隐式扩展)。因此,您不能仅仅因为在子构造函数中做了一些等效的事情就省略了父构造函数

关于java - 为什么我需要在这里明确地写一个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com