Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Final Keyword in Java

In this lesson, you will learn

  • Understanding Final in Inheritance
  • Examples

 

Final Keyword in Inheritance

The keyword final has three uses.

 

1. Creating Named Constant

The final use to make variables as constants. This means that once a final variable is initialized, its value cannot be changed.

Example

public class FinalVariableExample {
    public static void main(String[] args) {
        final int LIMIT = 5;
        // LIMIT = 10; // Uncommenting this line 
                 // would cause a compilation error
        System.out.println("The limit is: " + LIMIT);
    }
}

 

2. Using Final to Prevent Overriding

A final method cannot be overridden by subclasses.

This is useful when you want to lock down the implementation of a method to prevent any subclass from changing its behavior.

Example

public class Animal {
    public final void eat() {
        System.out.println("This animal eats food.");
    }
}

public class Dog extends Animal {
    // This method would cause a compilation error if uncommented
    //public void eat() {
    //    System.out.println("This dog eats biscuits.");
    //}
}

 

3. Using ‘final’ to Prevent Inheritance

When a class is declared as final, it cannot be subclassed.

This is particularly useful when creating an immutable class or a class that should not be extended for security reasons.

Example

public final class FinalClass {
    // Class body
}

// This would cause a compilation error
//public class AnotherClass extends FinalClass {
//    // Attempt to subclass FinalClass
//}

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review