in Java, Difference between the final method and the abstract method
In Java, final
methods and abstract
methods serve different purposes and have distinct characteristics. Here’s a breakdown of the differences between them:
Definition: A final
method is a method that cannot be overridden by subclasses. Once a method is declared as final
, its implementation is fixed and cannot be changed in any subclass.
Usage: The final
keyword is used to prevent method overriding. This is useful when you want to ensure that the behavior of a method remains consistent across all subclasses.
Implementation: A final
method must have a complete implementation. It cannot be abstract; it must provide a body.
Example:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// This will cause a compile-time error
// void display() {
// System.out.println("Trying to override final method.");
// }
}
Definition: An abstract
method is a method that is declared without an implementation (i.e., it does not have a body). It is meant to be overridden in subclasses.
Usage: The abstract
keyword is used to define a method that must be implemented by any non-abstract subclass. This is useful for defining a contract that subclasses must adhere to.
Implementation: An abstract
method cannot have a body and must be declared in an abstract
class. Any class that contains an abstract method must also be declared as abstract.
Example:
abstract class Animal {
abstract void makeSound(); // Abstract method
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
Feature | Final Method | Abstract Method |
---|---|---|
Definition | Cannot be overridden | Must be overridden |
Implementation | Must have a body | Cannot have a body |
Class Requirement | Can be in a regular class | Must be in an abstract class |
Purpose | To prevent modification of behavior | To define a contract for subclasses |
In summary, use final
methods when you want to lock down the implementation, and use abstract
methods when you want to enforce a certain behavior that subclasses must implement.