![]() |
VOOZH | about |
The final keyword in Java is used to restrict inheritance and method overriding. It can be applied to classes, methods, and variables to enforce specific behavior. When used with inheritance, final helps maintain consistency and prevents unwanted modifications in derived classes.
width of s1 : 10.0 height of s1 : 20.0 width of s2 : 10.0 height of s2 : 10.0 area of s1 : 200.0 area of s2 : 100.0
class Parent {
final void display() {
// code
}
}class Child extends Parent {
// display() cannot be overridden
}
A class declared as final cannot be inherited. This is useful when you want to create a complete and secure class whose behavior should not be modified through inheritance.
Syntax:
final class A {
// methods and fields
}
// Compilation Error
class B extends A {
}
This is a Vehicle class.
Explanation: The Vehicle class is declared as final, so no other class can extend it. The program creates an object of Vehicle and calls its display() method successfully.
Note :
- Declaring a class as final implicitly declares all of its methods as final, too.
- It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. For more on abstract classes, refer abstract classes in java
Declaring a method as final prevents subclasses from overriding it. This ensures that the method's implementation remains unchanged in all derived classes.
Syntax:
class A {
final void show() {
System.out.println("Final Method");
}
}
class B extends A {
// show() cannot be overridden
}
This is a Vehicle class.
Explanation: The sound() method in the Animal class is declared as final, so the Dog class inherits it but cannot override it. The program calls the inherited sound() method and the display() method of Dog.