PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] what is the use of inheriting a final method in java ? If we cant override it

 July 09, 2022     final, java, keyword, oop     No comments   

Issue

I was studying about java basics and came across this final keyword . And read that a final method can be inherited . But we cant override that method . Then what is use of inheriting any final method ? why to do that?


Solution

Inheritance

Inheritance of a method makes that method available for calling in a subclass. Calling a method is obviously useful.

When a method name is called on a subclass, the Java runtime looks first to see if the subclass has such a method. If found, that implementation of the method is executed. If not found, the Java runtime then looks to the superclass for such a method. If found, that implementation of the method is executed. If not found, the Java runtime looks to the superclass of the superclass, and so on.

Overrides

Overriding means you do not want to call the method in the superclass, and instead the subclass provides an alternative (or additional) behavior to be used when that method name is invoked. In some classes, allowing alternative/additional behavior may be risky.

Indeed, general opinion seems to be evolving towards the position that all methods should be final until the class author has determined a case where permitting specific overrides is necessary or useful enough to justify the potential risk. (A similar wisdom seems to be growing, in the position that classes should be initially designed as immutable until a specific need for mutability has been established.)

Sealed classes

The future feature of sealed classes/interfaces puts another spin on the issue. A sealed class allows inheritance only by an explicit list of subclasses known at compile-time.

In a sealed class, a method can be available for inheritance (non-final) only by its known subclasses. The risk of unintended behavior being added later by other classes is eliminated by the compiler and the Java runtime environment respecting the list of allowed subclasses.

You can try sealed classes as a preview feature now in Java 16. The feature is due for release in Java 17 coming 2021-09.



Answered By - Basil Bourque
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing