Junior — Middle
How to implement and apply abstract classes in Java?
sobes.tech AI
Answer from AI
In Java, an abstract class is a class that cannot be instantiated directly (you cannot call new), and it can contain both implemented methods and abstract methods (without implementation).
To declare an abstract class, the keyword abstract is used:
abstract class Animal {
abstract void makeSound(); // abstract method
void breathe() {
System.out.println("Breathing");
}
}
Classes that inherit from an abstract class must implement all abstract methods:
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
Usage:
- To create a common template for a group of classes.
- To declare methods that must be implemented in subclasses.
- To allow partial implementation of functionality.
It is used for organizing code and ensuring polymorphism.