The above program compile perfectly
protected members can't be accessed outside package using dot operator
Originally posted by srinivas marasu:
K&B book 1st chapter page no:-34
what does it mean for a subclass-outside-the-package to have access to a
superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. Protected does not mean that the subclass can treat the protected superclass member as though it were public. So if the subclass-outside-the-package gets a reference to the superclass (by, for example, creating an instance of the superclass somewhere in the subclass' code), the subclass cannot use the dot operator ]on the superclass
reference to access the protected member. To a subclass-outside-the-package, a protected member might as well be default (or even private), when the subclass is using a reference to the superclass. The subclass can see the protected member only through inheritance
in the first case you have used super keyword,
as per i know super is used to call constructor
of super class,how this possible
that we are accessing protected variables?
JK - In this case we are accessing super via inheritance. Super is always available to a subclass after the super constructor has been run. It is a special reference to the core essense/object of the subclass instance. Try setting super to a new instance of Test() and see what happens.
in the second case you have used this keyword..
As per i know this keyword refers
to current instance of class,as here current class is subTest
so instance variables of class subTest must be
called so how you can access protected members
of class Test?
JK - the current instance of subTest "inherits" any protected members of it's super class as if they were it's own members. There is no difference between it's own members and those it inherits from it's superclass. Unless of course subTest creates it's own member named "a". Try adding member int a = 15; to subTest. In this case subTest.a hides super.a.
Last case you have accessed directly protected variable
a.....how this is possible since both the
classes are in different packages atleast we need
a instance of subTest class to access variable a isnt it?
JK - Keep in mind that we are accessing and printing out the value of "a" within an instance of subTest via inheritance. The code is not accessing "a" from outside of subTest. Try creating another class in pack2 that tries to access mySubTestInstance.a.
After seeing these concepts of
protected access i am totally confused please
explain ......... [/QB]