-2

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.

Allen Yang
  • 81
  • 2
  • 10

3 Answers3

1

Yes it can. It's private methods that you can't access.

Softy
  • 23
  • 1
  • 5
0

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.

Community
  • 1
  • 1
DragShot
  • 341
  • 2
  • 10
0
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);
}
}
BHAR4T
  • 338
  • 3
  • 14