I am confused as to how protected members are accessed. In the KB book, it says that protected members are accessed only through inheritance. So if you try to access the member of a superclass in a subclass in a different package using the instance of the parent class then javac will through an error.
From your code, you already extended the ModifierTest. With that alone, the protected variable x is already visible int the Test class. You cannot access a protected member thru instantiating the superclass.Take note, inheritance is different from instantiation. You can only access protected members of the superclass thru inheritance.
I think the protected access modifier allows access to all classes within the same package and also all sub-classes(even if they are in different packages)
So if I have a class(B) in the same package as that of the protected member(in class A), then I can actually create an instance of class A in class B and use the protected member. Not exactly inheritance, since B is not a sub-class of A.
So protected access modifier is not "only" through inheritance. Outside the package--YES, but not within the same package.
Why is there no compile error in c. Isn't the protected member m2() accessed by creating an instance and not by inheritance? I am confused as to how the protected members can be accessed.
That code above will compile fine because C already inherited the public and protected properties of A. So it is legal to call method m2().
The first code you have mentioned is different from the 2nd one because from there you instantiated your superclass ModifierTest in your Test class (this is not inheritance) and tries to access the protected member, definitely it will not compile. The Dan's mock exam will compile fine because the superclass A was not instantiated...it was inherited and then it creates an instance of C in order to call the method m2() inherited from A. You need to instantiate C because you are in a static method (main method).
On the other hand, i do agree with the above explanation of Murtuza. [ August 13, 2004: Message edited by: arnel nicolas ]