Search code examples
javaclassinheritanceprotected

In Java, can a class access the protected attribute in the super class of its super class?


For example,

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!";
}
....
}

It is clear that class MultipleChoice can access the question, type, and correctAnswer in class Question. But when I try to access them in class TrueFalse bythis.a. I got an error. cannot be resolved or is not a field.

Thus, is the protected attribute in a class is only accessible in its subclass, but not sub-subclass? Three files are in the same package but different class file.


Solution

  • Well, I copy/pasted your code into an online compiler and tried it out. It worked, and you can find it here. That looks like a yes.

    I mean, if those were private fields it would make sense, but with the rest there shouldn't be a problem (unless it is package-access only).

    Are you declaring those classes in the same file? If one of those is a nested class, that might be the cause.

    Reply to old version

    Super-super field access, uh? Hmm...

    How about ((A)this).a? If the field is protected, maybe this could work.

    NOTE: If it still doesn't work for you, try using it inside a non-static method inside C.