我是 Java 新手,所以我可能在这里错过了一些东西 - 我在其他线程中查看,但我没有找到任何与我的问题非常相似的内容。我知道私有(private)变量不会被子类继承。我遇到的问题是,为什么 super();在我的子构造函数中识别我的基本构造函数中的字段?是因为父类中的构造函数是公共(public)的吗?即使它传递的变量是私有(private)的,子构造函数也会识别它们并传递它们吗?如有任何澄清,我们将不胜感激。
父类:
public abstract class BaseQuestion {
private String questions;
private float totalAttempts;
private float averageTime;
private float percentCorrect;
public BaseQuestion(String questions, float totalAttempts, float averageTime, float percentCorrect){
this.questions = questions;
this.totalAttempts = totalAttempts;
this.averageTime = averageTime;
this.percentCorrect = percentCorrect;
}
子类:
public class TrueFalseQuestion extends BaseQuestion{
public static int questionsCreated;
public TrueFalseQuestion(String question, float totalAttempts, float averageTime, float percentCorrect){
super(question, totalAttempts, averageTime, percentCorrect);
}
编译器没有给我上面的错误,这让我有点困惑......
谢谢,
最佳答案
子类中的构造函数不能“识别”父类(super class)中的字段,它接收到的一些参数恰好与父类(super class)中的属性同名,但它们在原理上是不同的。它们被分配给父类(super class)的字段,因为您正在调用 super()
来访问父类(super class)的构造函数,仅此而已。
关于java - 私有(private)变量和继承的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926769/