Java Interview Question #1 : Is Final Method more efficient in Java ?
Que 1. Final Vs Non Final Method, Which is more efficient ?
Answer : Final
- Final methods execute more efficiently than non final method.
- Compiler knows at compile time that a call to a final method won’t be overridden by some other method
Let’s See, How ?
Consider the final method,
package com.c4learn.inheritance; public class ShapeClass { final void setShape() { System.out.println("I am Inherited");; } public static void main(String[] args) { Circle c1 = new Circle(); c1.setShape(); } } class Circle extends ShapeClass { }
Whenever we create an object of the child class then compiler will check whether method written inside the parent class is overriden or not at run time.
final void setShape() { System.out.println("I am Inherited");; }
In this case compiler already knows that, method is declared as final so it does not waste time in checking whether method is final or not.