×

Java Programs

Java Practice

Java program to demonstrate example of final method

Final Method:

A final method can not override i.e. you can not redefine the function. But final method can be inherited because final keyword restricts the redefinition of the method.

Without Overriding method:

import java.util.*;

class Base {
    //final method
    public void displayMsg() {
        System.out.println("I'm in Base class - displayMsg()");
    }
}

public class FinalMethod extends Base {
    //Overriding the method displayMsg()
    public void displayMsg() {
        System.out.println("I'm in FinalMethod class - displayMsg()");
    }
    public static void main(String[] s) {
        FinalMethod B = new FinalMethod();
        B.displayMsg();
    }
}

Output

I'm in FinalMethod class - displayMsg()

With Overriding method:

import java.util.*;

class Base {
    //final method
    final public void displayMsg() {
        System.out.println("I'm in Base class - displayMsg()");
    }
}

public class FinalMethod extends Base {
    //Overriding the method displayMsg()
    public void displayMsg() {
        System.out.println("I'm in FinalMethod class - displayMsg()");
    }
    public static void main(String[] s) {
        FinalMethod B = new FinalMethod();
        B.displayMsg();
    }
}

Output

/FinalMethod.java:12: error: displayMsg() in FinalMethod cannot override displayMsg() in Base
    public void displayMsg() {
                ^
  overridden method is final
1 error

After removing final:

import java.util.*;

class Base {
    //final method
    public void displayMsg() {
        System.out.println("I'm in Base class - displayMsg()");
    }
}

public class FinalMethod extends Base {
    //Overriding the method displayMsg()
    public void displayMsg() {
        System.out.println("I'm in FinalMethod class - displayMsg()");
    }
    public static void main(String[] s) {
        FinalMethod B = new FinalMethod();
        B.displayMsg();
    }
}

Output

I'm in FinalMethod class - displayMsg()

Java Final Variable, Class, & Method Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.