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()




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.