In Java, an abstract class is a blueprint for other classes. It acts as a template and cannot be instantiated on its own. Instead, it’s meant to be extended by other classes to provide a common structure while allowing flexibility.
Key Features of Abstract Classes
- Definition: Declared using the
abstract
keyword. - Combination of Methods: Can have both abstract methods (no body, defined using
abstract
) and regular methods (with implementation). - Cannot Be Instantiated: You can’t create objects of an abstract class.
- Supports Inheritance: Allows subclasses to inherit and override its methods.
Why Use Abstract Classes?
Abstract classes are ideal when:
- You want to define common behavior for related classes.
- Some methods need to be implemented in the base class, while others are specific to subclasses.
Example of an Abstract Class
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();
// Regular method with implementation
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Woof! Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
myDog.eat();
}
}
Explanation
- The
Animal
class is abstract and has one abstract method,sound()
, and one regular method,eat()
. - The
Dog
class extendsAnimal
and provides its own implementation ofsound()
. - In the
Main
class, we create an object ofDog
(a subclass ofAnimal
) to call its methods.
When to Use an Abstract Class Over Interfaces?
- Use abstract classes when classes share common features and you want to provide default functionality.
- Use interfaces when you want to define a contract or behavior that multiple unrelated classes can implement.
Abstract classes are a powerful feature in Java, offering a balance between structure and flexibility, making your code more organized and easier to maintain.