Loading lessons...
Java Abstraction
Java Abstraction
Abstraction hides implementation details and only shows what is important. In Java you do this with abstract classes and abstract methods.
Abstract classes
- An abstract class cannot create objects.
- You must inherit from it.
- It can have both normal and abstract methods.
Abstract methods
An abstract method has no body, only a signature. The subclass must provide the body:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
Why abstract
- Force subclasses to implement specific methods.
- Define a common template while leaving details to subclasses.
- Helpful for large projects and teamwork.
Rules
- An abstract method must be in an abstract class.
- A subclass of an abstract class must implement all abstract methods (or also be abstract).
TL;DR
- Abstract classes cannot be instantiated.
- Abstract methods have a signature but no body.
- Subclasses must implement abstract methods.