Abstract class must be subclassed and final class cannot be subclassed.
In Java, an abstract class and a final class are two different concepts with distinct characteristics:
- Abstract Class:
- An abstract class is a class that cannot be instantiated on its own.
- It may contain both abstract (methods without a body) and concrete (methods with a body) methods.
- Abstract classes are meant to be subclassed. Subclasses must provide concrete implementations for all abstract methods unless they are also declared as abstract.
javaabstract class Shape {
abstract void draw(); // Abstract method
void resize() {
// Concrete method
}
}
- Final Class:
- A final class is a class that cannot be subclassed or extended. It is the end of the inheritance hierarchy.
- Once a class is declared as final, it cannot be extended by any other class.
javafinal class MyFinalClass {
// Class implementation
}
In summary, the key differences are:
- Instantiation:
- Abstract classes can’t be instantiated on their own but can be subclassed.
- Final classes can be instantiated but can’t be subclassed.
- Inheritance:
- Abstract classes are meant to be subclassed to provide concrete implementations for abstract methods.
- Final classes cannot be subclassed; they are the end of the inheritance hierarchy.
Understanding these differences is crucial when designing class hierarchies and choosing between abstraction and finality based on the desired behavior of your classes.