» » Final method in java with example programs

  • If we declare any method as final by placing final keyword then that method becomes final method.
  • The main use of final method in java is they are not overridden.
  • We can not override final methods in sub classes.
  • If we are using inheritance and we need some methods not to overridden in sub classes then we need make it final so that those methods can not be overridden by sub classes. 
  • We can access final methods in sub class but we can not overridden final methods.



Defining a final method in java:

  • Add final keyword to the normal method then it will become final method.
  1. public final void method(){
  2. //code
  3.  }

What happens if we try to override final methods in sub classes?


#1 : Java program to explain about final method in java

  1. package inheritance;
  2. /**
  3.  * final methods in java with example program
  4.  * @author www.instanceofjava.com
  5.  */
  6. public class A {
  7.  
  8.     int a,b;
  9.     
  10.     public final void show(){
  11.         System.out.println("A class show method");
  12.     }
  13. }

final method in java with example program

Can we access final methods in sub classes?

  • Yes we can access final methods in sub classes.
  • As mentioned above we can access all super class final methods in sub class but we can not override super call final methods.

#2 : Java program to explain about final method in java

  1. package inheritance;
  2. /**
  3.  * final methods in java with example program
  4.  * @author www.instanceofjava.com
  5.  */
  6. public class A {
  7.  
  8.     int a,b;
  9.     
  10.     public final void show(){
  11.         System.out.println("A class show method");
  12.     }
  13. }

  1. package inheritance;
  2.  
  3. /**
  4.  * final methods in java with example program
  5.  * @author www.instanceofjava.com
  6.  */
  7.  
  8. public class B {
  9.     
  10.  public static void main(String[] args){
  11.         
  12.         B obj = new B();
  13.         obj.show();
  14.        
  15.     }
  16. }

Output:
  1. A class show method

Top 10 Java interview questions on final keyword 

Static method vs final static method in java with example programs  

Final static string vs Static string in java  

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu