Answer: final method in java programs is used to stop being overridden in derived class. However, final method can be inherited in derived class.
Note that final methods can be used in any normal class and not only to java final class.
In below java code example, Insurance class is the base class that is having final method “public final void InsuranceQuote() “ and normal method “public void process()” . The derived class InsuranceAgent cannot override final method InsuranceQuote() for its own implementation and have to use base class InsuranceQuote() method, but can override process() method.
/*
* final method java program example
*/
//Base class
class Insurance {
// Cannot be overriden by child class
public final void InsuranceQuote() {
System.out.println("Insurance quote by company");
}
// can be overriden by child class
public void process() {
System.out.println("Process Insurance online");
}
}
// Derived class
class InsuranceAgent extends Insurance {
// Override process method from base class
// Insurance
public void process() {
System.out.println("Process Insurance offline");
}
public void ShowInsurancePlan() {
System.out.println("Show Insurance Plan");
}
// We cannot override it as in base class, it is final
/*
* public void InsuranceQuote(){
* System.out.println("Insurance quote by company"); }
*/
}
NOTES:
Final method can be overloaded in java programs, In below example, we have overload two final methods given below.
public final void InsuranceQuote()
public final void InsuranceQuote(String premium)
Example:
class Insurance {
// Cannot be overriden by child class
public final void InsuranceQuote() {
System.out.println("Insurance quote by company");
}
//Overloaded final method
public final void InsuranceQuote(String premium) {
System.out.println("Insurance quote by company");
}
// can be overriden by child class
public void process() {
System.out.println("Process Insurance online");
}
}
CONCLUSION:
- final method cannot be overridden in java
- final method can be overloaded in java.
- final method can be inherited in java
- final method cannot be abstract in java
Recommended to read the interview question: Can a method be final and abstract both in java?
Some frequently asked java interview questions related to final keyword
Can final method be overloaded in java ?
Answer: Yes, final method in java programs can be overloaded.
Can we inherit final method in java?
Answer: Yes, we can inherit final method.
Can we override final method in java?
Answer: No, we cannot override final method, but, just we can inherit. NOTE: Final method we make to stop overriding it in a class.
You may like reading another important interview question related to final – What is use of final class in java?