• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Protected Behaviour

 
Micheal John
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is the quote I got from K&B 1.4 book.


I want to test it.. below is the coding...







How can ClassThree has a access to protected method in ClassOne?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I suggest that you search this forum for the same topic. It has been discussed in depth not too long ago. Got no time now to search for it for you.
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because, the protected method becomes private to classes that try to subclass only in the same package. When you subclass in another package, then the protected member is still available.
 
Henry Wong
author
Marshal
Pie
Posts: 21497
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A protected method is accessable by any subclass, not just classes that directly inherit from it. Since ClassThree is a subclass of ClassOne (albeit not directly), it can access the protected methods.

Henry
 
Micheal John
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because, the protected method becomes private to classes that try to subclass only in the same package. When you subclass in another package, then the protected member is still available.


See the below coding where it contradicts..







All the above three classes in the same package p1. Class3 can able to access the protected method in Class1..


To Henry Wong:


A protected method is accessable by any subclass, not just classes that directly inherit from it. Since ClassThree is a subclass of ClassOne (albeit not directly), it can access the protected methods.


As per quotes, a protected method will be accessible by any sub class(which extends it) regardless of same/different packages...

When a protected method will not able available / become private? can u modify my above coding to suit it?
 
Henry Wong
author
Marshal
Pie
Posts: 21497
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per quotes, a protected method will be accessible by any sub class(which extends it) regardless of same/different packages...

When a protected method will not able available / become private? can u modify my above coding to suit it?


As far as I know, there is no way to inherit a protected method, in a manner that will make it private. (But I have never needed such functionality)

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic