Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help with Overriding

 
Kacee Saxena
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a query related to method overriding. As per my knowledge, overriding method in derived class can not restrict the access level of the overridden method in base class. So in below example,



final keyword should not be allowed in class Trying. Since final restricts the access and changing behavior of the method. However the code is working fine, so can anyone please help me understanding this.

Thanks
 
Arjan Kleene
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kacee Saxena wrote:I have a query related to method overriding. As per my knowledge, overriding method in derived class can not restrict the access level of the overridden method in base class. So in below example,



final keyword should not be allowed in class Trying. Since final restricts the access and changing behavior of the method. However the code is working fine, so can anyone please help me understanding this.

Thanks
Final is not an access level keyword. There are four access levels: public, protected, default and private. Default access level does not have a keyword.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kacee,

The final keyword does not restrict access. It only prevents the method from being overridden. So, if you create a subclass of Trying, you won't be able to create an overriding here() method.

John.
 
Kacee Saxena
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response

I was under impression that although final is not an access level keyword but somehow it puts a limitation on the method that it cant be overridden further. I think this is a kind of "restriction" being laid on the overridden method.
I still believe that the here() method's behavior has been restricted by adding "final" keyword since the concept behind overriding is to allow a method exhibit multiple behavior in child classes.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kacee:

The final keyword just tells the compiler to not allow the method to be overridden. It does not change any programmatic behavior. If you have an object of that class, you can still use that method (assuming that the access level allows that). Method behavior and compiler behavior are two different things.

John.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic