【问题标题】:In Java, can a class access the protected attribute in the super class of its super class?在Java中,一个类可以访问其超类的超类中的受保护属性吗?
【发布时间】: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


【解决方案1】:

是的,它可以。这是您无法访问的私有方法。

【讨论】:

  • 你是什么意思 onCreate 它的普通 java pc 应用程序而不是 android
【解决方案2】:

好吧,我将您的代码复制/粘贴到在线编译器中并进行了试用。它奏效了,你可以找到它here。看起来是的。

我的意思是,如果这些是私有字段,那将是有意义的,但其余的不应该有问题(除非它只是包访问)。

您是否在同一个文件中声明这些类?如果其中一个是嵌套类,那可能就是原因。

回复旧版

超级超级领域访问,嗯?嗯……

((A)this).a 怎么样?如果该字段受到保护,也许这可以工作。

注意:如果它仍然不适合您,请尝试在 C 中的非静态方法中使用它。

【讨论】:

  • @AllenYang 你在哪里写代码来访问字段a
  • @AllenYang 我只是复制/粘贴到一个通用的在线编译器并运行它而没有警告。
  • 它是有线的。实际上,我还在 MultipleChoice 的构造函数中使用了受保护的数据。这是一个原因吗?
【解决方案3】:
public class MultilevelVar {
public static void main(String[] args) {
new C().fun();
}
}

class A {
protected int x = 10;
}

class B extends A {
int x = 20;
}

class C extends B {
int x = 30;
void fun() {
System.out.println(((A) this).x);
System.out.println(((B) this).x);
System.out.println(((C) this).x);
}
}

【讨论】:

  • 您可以使用 n 层级的变量。
  • 是的,我在每个级别都声明了新的 x。
  • 这不是重点。默认情况下,受保护的字段从子类中可见。您的示例是通过创建另一个具有相同名称的字段来隐藏固有的受保护字段!
猜你喜欢
  • 2016-08-13
  • 2013-05-27
  • 2014-05-14
  • 2012-10-23
  • 2012-12-01
  • 2013-03-25
  • 2017-12-09
  • 2013-06-08
  • 2011-11-29
相关资源
最近更新 更多