Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, March 10, 2025

final methods and classes in Java

 

Final Methods and Classes in Java

The final keyword in Java is a non-access modifier used to indicate that something cannot be modified. It can be applied to classes, methods, and variables.


📌 1. Final Classes

A final class cannot be extended (inherited) by any other class. This is used when you want to prevent the class from being subclassed to protect its implementation.


Syntax

final class FinalClass {

    void display() {

        System.out.println("This is a final class.");

    }

}


Example of Final Class

final class Vehicle {  // Declaring a final class

    public void display() {

        System.out.println("Vehicle class display method.");

    }

}

 

// Attempt to inherit the final class (This will cause a compile-time error)

/*

class Car extends Vehicle {

    // Error: Cannot inherit from final 'Vehicle'

}

*/

 

public class Main {

    public static void main(String[] args) {

        Vehicle obj = new Vehicle();

        obj.display();

    }

}


Output

Vehicle class display method.


🔍 Explanation

  • The class Vehicle is declared as final, which prevents any class from extending it.
  • Trying to create a subclass like Car will result in a compile-time error.

📌 2. Final Methods

A final method cannot be overridden by any subclass. This is useful when you want to ensure that the implementation of a method remains unchanged.


Syntax

class Parent {

    final void display() {  // Declaring a final method

        System.out.println("This is a final method.");

    }

}


Example of Final Method

class Parent {

    final void display() {  // Final method

        System.out.println("Final method in Parent class.");

    }

}

 

class Child extends Parent {

    // Attempting to override a final method (This will cause a compile-time error)

    /*

    void display() {  

        System.out.println("Trying to override final method.");

    }

    */

}

 

public class Main {

    public static void main(String[] args) {

        Parent obj = new Parent();

        obj.display();

    }

}


Output

Final method in Parent class.


🔍 Explanation

  • The method display() in the Parent class is declared as final.
  • Attempting to override display() in the Child class will result in a compile-time error.

📌 3. Important Points to Remember

  1. Final Classes:
    • Prevent inheritance.
    • Commonly used to create immutable classes (e.g., String class in Java).
  2. Final Methods:
    • Prevent overriding.
    • Useful when a method's functionality must remain consistent across all subclasses.
  3. Use Cases:
    • Security: Prevent unauthorized overriding.
    • Performance: The compiler may optimize final methods since it knows they won't be overridden.
    • Immutability: Creating immutable classes by making classes final and providing only final fields.

 

No comments:

Post a Comment