Abstract Classes
Overview
An Abstract Class is a half-finished blueprint. It's a class that is so generic, you are not allowed to build an object directly from it (you cannot use `new`).
For example, think of a `Shape`. What does a generic 'Shape' look like? Nothing. You can draw a Circle or a Square, but you can't draw just a 'Shape'. So, we make `Shape` abstract. We can write some shared code in it (like a color variable), but we force child classes to figure out the specific details (like calculating area).
1. The Abstract Keyword
If you put `abstract` in front of a class, nobody can use `new` to create it. It MUST be used as a parent for another class.
2. Abstract Methods
You can create methods that have NO code inside them (no curly braces). You are essentially saying: 'I don't know how to do this, the child class MUST write the code for this.'
Syntax
The Shape class doesn't know how to calculate area, so it forces the Circle to figure it out.
// You CANNOT do: new Shape();
public abstract class Shape {
String color = "Red"; // Shared data
// Abstract method (No body! No curly braces!)
// Every child MUST write the code for this.
public abstract void calculateArea();
}
public class Circle extends Shape {
// The child is FORCED to implement the missing method
@Override
public void calculateArea() {
System.out.println("Area is Pi * R * R");
}
}Common Pitfalls
- Trying to use `new` on an abstract class. The compiler will immediately throw an error.
- A child class inheriting from an abstract class but forgetting to write the code for the abstract methods.
Interview Tips
- Use abstract classes when objects share a lot of core logic (like an ID or a name), but have entirely different ways of executing a specific action.
Real-World Example
A payment gateway has an abstract `Payment` class. It handles logging and security, but leaves the actual `chargeMoney()` method abstract for `PayPal` and `CreditCard` classes to figure out.
public abstract class Payment {
public void logTransaction() { System.out.println("Logging..."); }
public abstract void chargeMoney(double amount);
}