[!NOTE] The final pillar of Object-Oriented Programming is Abstraction. It focuses on hiding complex implementation details from the user, leaving only the high-level essential features visible.
In Java, we achieve the strictest form of Abstraction using the abstract keyword.
The Problem with Generic Classes
Consider the Animal parent class from the previous chapter.
Animal mysteriousThing = new Animal();
mysteriousThing.makeSound(); // ???
Conceptually, a "pure generic animal" does not exist in the real world. You can have a Dog or a Cat, but you cannot literally spawn an "Animal". It's too vague.
Furthermore, we know every single animal makes a sound, but what sound does a generic Animal make? We don't know yet! We need a way to force all children to implement a makeSound() method, without us having to guess what it is in the Parent.
The Abstract Class
By applying the abstract keyword to a class, you permanently restrict it. An abstract class cannot be instantiated using the new keyword. It exists solely to be inherited by child classes.
Furthermore, inside an abstract class, you can declare Abstract Methods. These are methods that have no body (no curly braces). They act as a strict contract: any child class that inherits this parent must write the code for these methods, or the child will refuse to compile!
// 1. We lock the class so nobody can do 'new Animal()' anymore
abstract class Animal {
String name;
// Regular methods are still totally fine here!
public void sleep() {
System.out.println("Zzz...");
}
// 2. ABSTRACT METHOD! No body. It forces children to implement it.
public abstract void makeSound();
}
// 3. The Child Class
class Pig extends Animal {
// If the Pig class doesn't override makeSound, the Java Compiler will throw a massive error!
@Override
public void makeSound() {
System.out.println("Oink oink!");
}
}
public class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Totally fine
myPig.makeSound();
myPig.sleep(); // Inherited regular method
// Animal a = new Animal(); // ERROR: Cannot instantiate abstract class!
}
}
Summary of Rules
- Abstract classes can have both abstract methods and regular methods.
- An abstract method can ONLY exist inside an abstract class.
- You cannot create objects from an abstract class. It is a strictly parent-level blueprint template.