• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about protected methods

 
Sudarshan Sreenivasan
Ranch Hand
Posts: 188
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// 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
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sudarshan Sreenivasan
Ranch Hand
Posts: 188
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic