An abstract class in Java is a class that cannot be instantiated and is designed to be inherited. It may contain abstract methods (without implementation) as well as concrete methods (with implementation).
abstract keywordAn abstract method does not have a body and must be implemented by child classes. If a class contains at least one abstract method, the class itself must be declared abstract.
// Abstract class defining a common structure
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Animal is sleeping");
}
}
// Concrete class implementing abstract methods
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// Main class to test abstract class behavior
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
a.sleep();
}
}
Dog barks
Animal is sleeping
The abstract reference Animal points to a Dog object. The implemented sound() method of Dog is executed at runtime.
See how the Shape abstract class works with different implementations. Change the inputs below and run the Java code.
Shape with method area()Circle and Rectangle classes