Introduction to Abstract Classes in Java
In Java programming, abstract classes serve as blueprints for other classes. They can contain abstract methods, which are methods without a body, as well as concrete methods with implementations. This tutorial will delve into the concept of abstract classes, their syntax, purpose, and usage in Java.
What is an Abstract Class?
An abstract class in Java is a class that cannot be instantiated on its own and typically exists to be subclassed. It may contain abstract methods, concrete methods, instance variables, constructors, and static methods. Abstract classes are used to define a common interface for a group of subclasses while leaving the implementation of some methods to the subclasses.
Syntax of Abstract Classes
To declare an abstract class in Java, you use the abstract
keyword before the class
keyword. Abstract methods within the abstract class are also marked with the abstract
keyword. Here’s the syntax:
abstract class AbstractClassName {
// Abstract method declaration
abstract void abstractMethod();
// Concrete method
void concreteMethod() {
// Method implementation
}
}
Example of an Abstract Class in Java
Let’s create an abstract class Shape
with an abstract method calculateArea()
to calculate the area of different shapes. We’ll also include a concrete method display()
, which prints a message.
abstract class Shape {
// Abstract method to calculate area
abstract double calculateArea();
// Concrete method to display a message
void display() {
System.out.println("This is a shape.");
}
}
Now, let’s create subclasses of Shape
, such as Rectangle
and Circle
, to implement the abstract method calculateArea()
.
class Rectangle extends Shape {
double length;
double width;
// Constructor
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementation of abstract method
double calculateArea() {
return length * width;
}
}
class Circle extends Shape {
double radius;
// Constructor
Circle(double radius) {
this.radius = radius;
}
// Implementation of abstract method
double calculateArea() {
return Math.PI * radius * radius;
}
}
Using Abstract Classes in Java
You can create objects of the subclasses and call their methods, including the abstract method inherited from the abstract class.
public class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 3);
Circle circle = new Circle(4);
rect.display();
System.out.println("Area of rectangle: " + rect.calculateArea());
circle.display();
System.out.println("Area of circle: " + circle.calculateArea());
}
}
Conclusion
Abstract classes in Java provide a powerful way to define common behavior for a group of subclasses while allowing specific implementations to be deferred to those subclasses. By understanding abstract classes and their usage, you can write more modular and maintainable Java code.