An abstract class defines a new type of data (just like an interface or class) but can optionally not provide implementation for some of it's methods (these are called abstract methods). Similarly to interfaces abstract classes can also not be instantiated.
When a class extends an abstract class it must provide an implementation for all abstract methods defined in the class, or be marked as an abstract class itself.
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
public abstract void sound();
// Regular method with implementation
public void breathe() {
System.out.println("This animal breathes.");
}
}
// Concrete class that extends the abstract class
class Dog extends Animal {
// Providing implementation for the abstract method
public void sound() {
System.out.println("The dog barks.");
}
}
class Main {
public static void main(String[] args) {
// Cannot instantiate an abstract class directly
// Animal animal = new Animal(); // This would cause an error
// Instantiate the concrete subclass
Animal dog = new Dog();
dog.sound(); // Calls Dog's implementation of sound()
dog.breathe(); // Calls Animal's implementation of breathe()
}
}