Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access modifiers

 
Shruthi Sam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Suppose i am having a class x which contains a protected method. The class x resides in a package say A. Now another class in package B extends this class x in package A and tries to override the protected method in class x. Now what will be the access modifier of this method in the subclass? Is it private? will the compiler fail if we assign "weaker" privileges to the overriden methods? Please clarify.


 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try to implement . what error you are getting in compile-time ? Google for private,package-private(default),protected,public access specifiers
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while overriding the method the scope/access of the method cannot be more restricted.

For eg, in your case the protected method can be overriden with public and protected modfier. if you put private, compile time error will be there

similarily public method cannot become protected ...
 
Shruthi Sam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Harshit.. I understood.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harshit Rastogi wrote:
For eg, in your case the protected method can be overriden with public and protected modfier. if you put private, compile time error will be there

Even can't extends class X since it is in different package
 
Shruthi Sam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can import the package and extend the class. It will work.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shruthi Sam wrote:you can import the package and extend the class. It will work.


for that class needs to be public
 
Shruthi Sam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes it should be. Sorry, i forgot to mention that.
 
vvv gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Yes Shruti
while overriding the method the scope/access of the method cannot be more restricted.
This is the rule for overriding.

Subclass can add to funcnality whtever it recived from base class It cannot retrict its behaviour.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic