【发布时间】:2023-04-09 09:36:01
【问题描述】:
例如,
public class Question {
protected String question, correctAnswer, type;
....
}
public class MultipleChoice extends Question{{
...
}
public class TrueFalse extends MultipleChoice{
public TrueFalse(){
this.type = "TrueFalse";
this.question = "Question is not assinged!";
this.correctAnswer = "Correct Answer is not assinged!";
}
....
}
很明显class MultipleChoice可以访问class Question中的question, type, and correctAnswer。但是当我尝试在class TrueFalse bythis.a 中访问它们时。我有一个错误。
cannot be resolved or is not a field.
那么,类中的protected属性是否只能在其子类中访问,而不能在子子类中访问?三个文件在同一个包中,但是不同的类文件。
【问题讨论】:
-
请澄清,因为它在这里工作正常(如上所述)。
-
请提供完整的minimal reproducible example。
-
仅作记录:您确定多项选择不会重新声明这些字段?
-
@GhostCat 我实际上在 MultipleChoice 的构造函数中使用了它们。
-
它基本上是protected的定义,任何可以访问受保护属性的类的子类本身都可以访问该属性。
标签: java class inheritance protected