An abstract class is a class that cannot be instantiated on its own and is meant to be subclassed. It serves as a blueprint for other classes, providing a common structure that derived classes can implement or override.
// Abstract class
abstract class Animal {
// Instance variable
private String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Abstract method (no implementation)
public abstract void makeSound();
// Concrete method (with implementation)
public void eat() {
System.out.println(name + " is eating.");
}
// Getter for name
public String getName() {
return name;
}
}
// Subclass of Animal
class Dog extends Animal {
// Constructor
public Dog(String name) {
super(name);
}
// Implementing abstract method
public void makeSound() {
System.out.println(getName() + " says: Woof Woof");
}
}
// Subclass of Animal
class Cat extends Animal {
// Constructor
public Cat(String name) {
super(name);
}
// Implementing abstract method
public void makeSound() {
System.out.println(getName() + " says: Meow Meow");
}
}
// Main class to test the abstract class and its subclasses
public class Main {
public static void main(String[] args) {
// Creating objects of the subclasses
Animal dog = new Dog("Buddy");
Animal cat = new Cat("Whiskers");
// Calling methods
dog.makeSound();
dog.eat();
cat.makeSound();
cat.eat();
}
}
Buddy says: Woof Woof
Buddy is eating.
Whiskers says: Meow Meow
Whiskers is eating.
Animal
: This class cannot be instantiated. It has an abstract method makeSound()
that must be implemented by any subclass. It also has a concrete method eat()
that can be inherited by subclasses.Dog
and Cat
: These classes extend the Animal
class and provide implementations for the abstract method makeSound()
.Main
class, we create instances of Dog
and Cat
, and call their methods to demonstrate the functionality.