Letโ€™s explain final in Java in easy, everyday language โ€” with clear examples so you fully get it.


โœ… What Does final Mean in Java?

In simple terms:

final means โ€œyou canโ€™t change it later.โ€

It is used when you want to make something unchangeable โ€” like a lock that prevents future changes.


๐Ÿ› ๏ธ Where Can You Use final in Java?

You can use final with:

  1. Variables (canโ€™t change the value)
  2. Methods (canโ€™t override them)
  3. Classes (canโ€™t extend/inherit them)

Letโ€™s break them down one by one.


๐Ÿ”น 1. final Variable

Once you assign a value to a final variable, you canโ€™t change it.

๐Ÿ“ฆ Example:

public class Demo {
public static void main(String[] args) {
final int speedLimit = 60;
// speedLimit = 80; // โŒ Error: can't change a final variable
System.out.println("Speed Limit is: " + speedLimit);
}
}

โœ”๏ธ speedLimit is final โ€” you can set it once, but not change it.

This is useful when you want to declare constants like PI, tax rate, or max limit.


๐Ÿ”น 2. final Method

You can mark a method as final so that no subclass can override it.

๐Ÿ“ฆ Example:

class Vehicle {
final void start() {
System.out.println("Vehicle started");
}
}

class Car extends Vehicle {
// void start() { } // โŒ Error: can't override final method
}

โœ”๏ธ Once a method is marked final, no class that inherits it can change its behavior.


๐Ÿ”น 3. final Class

A final class cannot be extended (inherited).

๐Ÿ“ฆ Example:

final class Animal {
void sound() {
System.out.println("Animal sound");
}
}

// class Dog extends Animal {} // โŒ Error: can't extend a final class

โœ”๏ธ You use a final class when you donโ€™t want anyone to change or extend your class โ€” it’s locked.


๐Ÿ”„ Bonus: final with Objects

If you make an object final, you canโ€™t change the object reference, but you can change the data inside.

๐Ÿ“ฆ Example:

public class Demo {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // โœ… Allowed
// sb = new StringBuilder("Hi"); // โŒ Not allowed
System.out.println(sb); // Output: Hello World
}
}

โœ”๏ธ The object is final โ€” you canโ€™t reassign it โ€” but you can change what’s inside it.


๐Ÿง  Summary

Use of finalWhat it doesExample
VariableCan’t change its valuefinal int x = 10;
MethodCan’t override it in subclassfinal void run()
ClassCan’t be extended (inherited)final class Animal

๐ŸŽฏ Think of final as:

  • A lock ๐Ÿ”’ โ€” once used, no one can change or override it.
  • A way to protect values, methods, or class designs.

Leave a Reply

Your email address will not be published. Required fields are marked *