An abstract class is a partially implemented class that serves as a blueprint for its subclasses. It cannot be instantiated directly and is used when multiple related classes share common behavior while requiring their own specific implementations.
Key Points: • An abstract class is declared using the abstract keyword. • It can contain both abstract methods (without implementation) and concrete methods (with implementation). • Abstract methods must be implemented by the first concrete subclass. • An abstract class can have constructors, instance variables, and static methods. • It is useful when you want to provide common functionality while enforcing specific behavior in child classes.
Example: Consider a Vehicle abstract class with a start() method implemented and a fuelType() method declared as abstract. Different vehicle types such as Car and Bike can provide their own implementation of fuelType().
Code Example:
abstract class Vehicle {
abstract void fuelType();
void start() {
System.out.println("Vehicle Started");
}
}
class Car extends Vehicle {
@Override
void fuelType() {
System.out.println("Petrol");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start();
vehicle.fuelType();
}
}Interview Tip: A concise interview answer is:
"An abstract class is a class that cannot be instantiated and may contain both abstract and concrete methods. It is used to provide common functionality while forcing subclasses to implement specific behaviors."