OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 8 : Final Class and Methods in Java

 

Unit - 2

Topic - 8 : Final Class and Methods in Java

The final keyword in Java can be applied to classes, methods, and variables.
In this section, we will focus on its use with classes and methods.


1. Final Class

A final class is a class that cannot be inherited.
Once a class is declared as final, no other class can extend it.

Uses of Final Class

  1. Prevent Inheritance

    • Example: All wrapper classes in Java (Integer, Float, Double, etc.) are final.

  2. Create Immutable Classes

    • Example: The predefined String class is final, ensuring that its state cannot be changed after creation.


Example: Final Class

final class A { void display() { System.out.println("This is a final class."); } } // The following is illegal and will cause a compile-time error // class B extends A { } // ❌ Compile Error public class FinalClassDemo { public static void main(String[] args) { A obj = new A(); obj.display(); } }

Output:

This is a final class.

2. Final Method

A final method is a method that cannot be overridden in subclasses.
If you declare a method as final, all derived classes must use the same implementation.


Example: Final Method

class A { final void m1() { System.out.println("This is a final method."); } } class B extends A { // ❌ The following will cause a compile-time error /* void m1() { System.out.println("Trying to override - Not Allowed!"); } */ } public class FinalMethodDemo { public static void main(String[] args) { B obj = new B(); obj.m1(); } }

Output:

This is a final method.

Key Points

  • A final class cannot be extended.

  • A final method cannot be overridden.

  • The final keyword is often used to:

    • Ensure security and prevent unwanted changes.

    • Maintain consistent method behavior across subclasses.

    • Create immutable classes.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies