Why can’t my subclass access a protected variable of its superclass, when it’s in a different package?

It works, but only you the children tries to access it own variable, not variable of other instance ( even if it belongs to the same inheritance tree ). See this sample code to understand it better: //in Parent.java package parentpackage; public class Parent { protected String parentVariable = “whatever”;// define protected variable } // … Read more

Should you ever use protected member variables?

Should you ever use protected member variables? Depends on how picky you are about hiding state. If you don’t want any leaking of internal state, then declaring all your member variables private is the way to go. If you don’t really care that subclasses can access internal state, then protected is good enough. If a … Read more

Protected access modifier in Java

The webpage @MadProgrammer linked gives a decent explanation: “The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.” This means the protected member must be accessed directly through either the class it is defined in … Read more

accessing a protected member of a base class in another subclass

When foo receives a FooBase reference, the compiler doesn’t know whether the argument is a descendant of Foo, so it has to assume it’s not. Foo has access to inherited protected members of other Foo objects, not all other sibling classes. Consider this code: class FooSibling: public FooBase { }; FooSibling sib; Foo f; f.foo(sib); … Read more

tech