An abstract class in Java is a class that cannot be instantiated, meaning you cannot create an object of that class directly. Instead, abstract classes are intended to serve as base classes for other classes to inherit from. An abstract class may contain abstract methods, which are methods without a body. An abstract method must be implemented by a subclass.
The purpose of an abstract class is to provide a common interface for a set of related classes. By defining abstract methods in the abstract class, the designer is specifying a set of methods that must be implemented by any subclass that inherits from the abstract class.
Here’s an example of an abstract class in Java:
public abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
In this example, the Shape
class is an abstract class that defines two abstract methods: getArea()
and getPerimeter()
. The Rectangle
and Circle
classes inherit from the Shape
class and provide their own implementations of the getArea()
and getPerimeter()
methods.
Abstract classes are useful when you have a set of related classes that share a common interface, but have different implementations. By defining the common interface in an abstract class, you can ensure that all the subclasses implement the necessary methods, and you can provide a common set of methods that can be used to manipulate instances of the subclasses.