- 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.
- public final void method(){
- //code
- }
What happens if we try to override final methods in sub classes?
#1 : Java program to explain about final method in java
- package inheritance;
- /**
- * final methods in java with example program
- * @author www.instanceofjava.com
- */
- public class A {
- int a,b;
- public final void show(){
- System.out.println("A class show method");
- }
- }
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
- package inheritance;
- /**
- * final methods in java with example program
- * @author www.instanceofjava.com
- */
- public class A {
- int a,b;
- public final void show(){
- System.out.println("A class show method");
- }
- }
- package inheritance;
- /**
- * final methods in java with example program
- * @author www.instanceofjava.com
- */
- public class B {
- public static void main(String[] args){
- B obj = new B();
- obj.show();
- }
- }
Output:
- 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
package inheritance;
ReplyDelete/**
* final methods in java with example program
* @author www.instanceofjava.com
*/
public class B extends A{
public static void main(String[] args){
B obj = new B();
obj.show();
}
}
extends A is missing in program.