In Java method can be declared as final using final
keyword. If a method is declared as final then it can't be overridden by the
subclasses. Making methods to final protects it from unexpected behavior from a
subclass alteration of method. If a constructor calls the method then this
method should generally be declared as final because if a non-final method is
called by the constructor then it may be redefined by subclass.
Syntax for declaring a method as final:-
public class className { public final void methodName1() { ...... } public static final void methodName2() { ...... } }
|
But, when you extends the class which contains the final method then the overriding of final method is not allowed.
public class test{ public final void methodName1() { ......} public static final void methodName2() { ......} } public class rock extends test { public void methodName1() { ......} public static void methodName2() { ......} } |
A final method cannot be overridden. Which means even
though a sub class can call the final method of parent class without any issues
but it cannot override it.
Example:
class X{ final void demo(){ System.out.println("X Class Method"); } } class A extends X{ void demo(){ System.out.println("A Class Method"); } public static void main(String args[]){ A obj= new A(); obj.demo(); } }
|
The above program would throw a compilation error, however we can use the parent class final method in sub class without any issues. Lets have a look at this code: This program would run fine as we are not overriding the final method. That shows that final methods are inherited but they are not eligible for overriding.
Example:-
class X{ final void demo(){ System.out.println("X Class Method"); } } class A extends x{ public static void main(String args[]){ A obj= new A(); obj.demo(); } }
|