posted 20 years ago
Here is the rule for protected members
a) protected members can be accessed by other classes in the same package
b) For subclasses outside the package , the protected member can be accessed only through inheritance. A subclass outside the package cannot access a ptotected member using a reference to the instance of the super class.
Example:
package p1;
public class A{
protected int acctNo;
...
}
package p2;
public class B extends A{
private void method1(){
A newclassA = new A().acctNo; // compile error
}
}
Logical reason: When one class extends another class , instances of subclass wil contain their own copy of all members of super class and sub class. Which means , instance of class B has a copy of variable acctNo, whose visibility is protected so the subclass can access its variable acctNo. This confirms rule b) You can access the acctNo through inheritance means "subclass copy can be accessed by subclass B " . In your example q is the instance of super class , so class B does not have access to super class protected members using super class instance.
Just remember the rule b and INHERITANCE.
There is one more weirdo scenario where "if the subclass creates another instance of subclass say B1 , subclass B has access to B1's acctno"
{ Winners do what losers don't do }