- it is a class in java that can’t be instantiated but is used as a blueprint for other classes. it is designed to be extended by subclasses.
- it is declared using keyword
abstract.
- it may contain
- abstract methods - methods without a body, must be implemented by subclass
- concrete methods - methods with implementation that subclasses use or override.
- fields - constructors and nested classes.
- cannot be instantiated.
- purpose -
- provide a common structure and behavior for related classes.
- enforces a contract by requiring subclasses to implement abstract methods.
- enables code reuse through shared fields and methods.
- support polymorphism by allowing abstract class references to point to subclass objects.
abstract class Animal {
String name;
// Constructor
Animal(String name) {
this.name = name;
}
// Abstract method (must be implemented by subclasses)
abstract void makeSound();
// Concrete method (shared by all subclasses)
void sleep() {
System.out.println(name + " is sleeping.");
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // Call superclass constructor
}
@Override
void makeSound() {
System.out.println(name + " says Woof!");
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " says Meow!");
}
}
class Main {
public static void main(String[] args) {
// Animal animal = new Animal("Generic"); // Error: Cannot instantiate
Animal dog = new Dog("Buddy");
Animal cat = new Cat("Whiskers");
dog.makeSound(); // Output: Buddy says Woof!
dog.sleep(); // Output: Buddy is sleeping.
cat.makeSound(); // Output: Whiskers says Meow!
cat.sleep(); // Output: Whiskers is sleeping.
}
}