What is final
in Java?
The final
keyword in Java is used to restrict the user.
Depending on where it's used, it means:
Used With | Meaning |
---|---|
final variable |
Value cannot be changed (constant) |
final method |
Method cannot be overridden in subclasses |
final class |
Class cannot be inherited |
1. final
Variable (Constant)
public class FinalVariableExample {
public static void main(String[] args) {
final int SPEED_LIMIT = 100; // constant
System.out.println("Speed Limit: " + SPEED_LIMIT);
// SPEED_LIMIT = 120; // ❌ Error: cannot assign a value to final variable
}
}
Once a variable is declared
final
, its value cannot be changed.
2. final
Method (Prevent Overriding)
class Animal {
final void sound() {
System.out.println("Animals make sound");
}
}
class Dog extends Animal {
// ❌ Cannot override final method
// void sound() {
// System.out.println("Dog barks");
// }
}
public class FinalMethodExample {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Output: Animals make sound
}
}
Declaring a method
final
ensures that child classes cannot override it.
3. final
Class (Prevent Inheritance)
final class Vehicle {
void drive() {
System.out.println("Vehicle is moving");
}
}
// ❌ Error: Cannot inherit from final class
// class Car extends Vehicle {}
public class FinalClassExample {
public static void main(String[] args) {
Vehicle v = new Vehicle();
v.drive();
}
}
A
final
class cannot be extended by any other class.
Bonus: Final Reference Variable (Object)
class Student {
int id;
Student(int id) {
this.id = id;
}
}
public class FinalReferenceExample {
public static void main(String[] args) {
final Student s = new Student(101);
System.out.println(s.id);
s.id = 202; // ✅ Allowed: modifying object content
// s = new Student(303); // ❌ Not allowed: reassigning final reference
}
}
You can modify the fields of a final object, but cannot reassign it to a new object.
Summary
Final Keyword Used With | Restriction |
---|---|
final variable |
Value can’t be changed (constant) |
final method |
Cannot be overridden in subclass |
final class |
Cannot be extended (inherited) |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.