Can an abstract class have a constructor?
Yes, an abstract class can have a constructor in Java. The purpose of the constructor in an abstract class is to allow subclasses to initialize the state of the object when they are created.
Here's an example of an abstract class with a constructor:
abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
public abstract double getArea();
public String getColor() {
return this.color;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * this.radius * this.radius;
}
}
In the example above, the Shape
class is an abstract class that has a constructor that takes a color
parameter. The Circle
class extends the Shape
class and calls the superclass constructor using the super
keyword to initialize the color
field of the Shape
object.