wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about protected methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about protected methods" Watch "about protected methods" New topic
Author

about protected methods

Sudarshan Sreenivasan
Ranch Hand

Joined: Jun 28, 2007
Posts: 188

// Super.java

package p1 ;
public class Super {
protected void say ( String s ) {
System.out.println ( s ) ;
}
}

// SubOne.java

package p1 ;
public class SubOne extends p1.Super { }

// SubTwo.java

1. package p2 ;
2. public class SubTwo extends p1.Super {
3. public static void main ( String [ ] args ) {
4. p1.Super s = new p1.Super() ;
5. p1.SubOne s1 = new p1.SubOne () ;
6. SubTwo s2 = new SubTwo() ;
7. s.say (" Super ") ;
8. s1.say ("SubOne") ;
9. s2.say ("SubTwo") ;
10. }
11. }


On compile the code we get compile time errors at statements 7 and 8 .... according to me the errors are because we are trying to access say() through the reference of the super class !!

While the concept says that a protected member can be accesed only via the reference of the child class (SubTwo ) or any of its subtypes....


Please let me know if i am wrong !!

Thanks
Priyam Srivastava
Ranch Hand

Joined: Oct 29, 2006
Posts: 169
up you are right...protected members outside the package can only be referenced through the reference variable of the sub-class & outside the package they behave(logically & not technically) as the private member of that sub-class.


"History would be kind to me, for I intend to write it."
Sudarshan Sreenivasan
Ranch Hand

Joined: Jun 28, 2007
Posts: 188




Just rearranged the code a little !!

I think it should becausse the method say() is protected and SubTwo does not inherit from Subone ... so say() should not be visible in SubTwo ..... please correct me if i am wrong !!

Thanks
Mallik Avula
Ranch Hand

Joined: Nov 30, 2006
Posts: 86
Hi Sree,
the answer to your question is yes.
Because SubOne is inheriting the protected say() from Super. so now it is private in SubOne.
So there is no way to access private members outside the class.
"Protected members will become private in subclasses outside of the package".
reference: page no: 70,71 K & B.
i hope it helps you.


Thanks & Regards<br />Mallik Avula<br />SCJP1.4
 
GeeCON Prague 2014
 
subject: about protected methods