hi,i m preparing for SCJP i m having one doubt that--->if superclass A having one protected member x and Class B in diff package extends this class A ..will the result is x is inherited to B but it x now become private to B...??? and if some other class C extends B....how it able to accesss x ???
Originally posted by Stuart Gray: A protected variable is available to all subclasses (and subclasses of those classes) regardless of the package they are in. They don't 'become private' or anything like that.
False, sorta. They do become "private".
Here's the deal. String foo in A has no access modifier so any class in that package has access. String in A is changed to protected. Access expands to include immediate subclasses.
The emphasis is important. If B extends A it has access to String foo. If C extends B, String foo is private for all intents and purposes. C will not have access to String foo even.
Originally posted by Rick O'Shay: The emphasis is important. If B extends A it has access to String foo. If C extends B, String foo is private for all intents and purposes. C will not have access to String foo even.
I could not believe that and I tried it out. Result: C can access foo. That is what I got from the language specification and that is what Sun's 1.4.2 compiler thinks.
A has a protected member x (in package a) B extends A (in package b) C extends B (in package c)
C can access x
Maybe it's in the specification that x should not be accessible by C but someone please prove it with a paragraph in the spec. I am 100% sure that I can access x in class C in JDK 1.4.2. If it is stated in the specification then it must be a bug.
Guys, just be clear what is meant by accessing a superclass's protected member. The subclass can inherit it but cannot make an instance of the parent class and then access the member by using the dot operator. Here is some code in the subclass.
So, the inherited protected member can be read by or written to by the subclass - but that subclass cannot give anyone else access to it! Another class which has a reference to the subclass cannot use that reference to see it. This means that the superclass's protected member becomes effectively a private member in the subclass.
To reiterate: a protected member's access is restricted just to inheritance. If you understand this, you won't go far wrong.