This is a protected inheritance question. I do understand that protected means that in a package, it is as if it is public. Outside a package, generally speaking it is only accessible when you are INSIDE the subclass. That is not my confusion. My confusion is on a little nit pick that is occurring and I do not know why. I will explain the guts of the question after the code. You are given packages com.wobble.foo which holds the TestA class and com.wobble.bar which holds the TestB class which extends classA.
//A Package
package com.wobble.foo;
public class TestA{
static protected int x = 5;
protected int y = 6;
}
//A different Package
package com.wobble.bar;
public class TestB extends TestA{
static{
TestA t = new TestA();
t.x = 1; //compiles
t.y = 2; //field not visible, fails to compile
}
}
The super class has a two variables both protected, one static. The subclass in a different package created a new superclass object attempting to access those two variables. Why are you able to, via the object, access the static variable through it, but not access the instance variable through it? They are both protected. Both from the same class. Both access by the same object. Note, to those who think this might be a duplicate: the other questions simply ask how protected works, but they fail to ask the specific question, of why only one of these two variables, both protected, can be accessed.
This is not a how-to-fix-the-code question. I know how to make the end game work. The question is why it is accessible via t.x;
but not t.y;
?