Abstraction is the process of hiding the internal details and showing only the essential features.
Abstract Class: A "half-finished" class. You can define some methods with code and leave others as "ideas" (abstract methods) for the children to finish.
Interface: A "contract." It’s a 100% abstract list of rules. If a class "implements" an interface, it promises to write the code for every method listed in that interface.
The Difference
Use an Abstract Class if the objects are related (e.g., a "Bird" and a "Plane" both fly, but they are different things).
Use an Interface if you want to define a specific capability (e.g., anything—from a phone to a credit card—can be "Payable").
The Code Example:
// 1. The Interface (The Contract)
interface Playable {
void play(); // No code here! Just the "idea" of playing.
}
// 2. The Abstract Class (The Half-Finished Blueprint)
abstract class Instrument {
String name;
// Regular method: All instruments are cleaned the same way
void clean() {
System.out.println("Cleaning the instrument...");
}
// Abstract method: Every instrument is played differently!
abstract void tune();
}
// 3. The Concrete Class (The Finished Product)
class Guitar extends Instrument implements Playable {
@Override
void tune() {
System.out.println("Tightening the guitar strings...");
}
@Override
public void play() {
System.out.println("Strumming a C-major chord!");
}
}
public class Main {
public static void main(String[] args) {
// You CANNOT do: Instrument i = new Instrument(); (It's abstract!)
Guitar myGuitar = new Guitar();
myGuitar.clean(); // From Abstract Class
myGuitar.tune(); // Completed from Abstract Class
myGuitar.play(); // Completed from Interface
}
}Expected Output:
Cleaning the instrument...
Tightening the guitar strings...
Strumming a C-major chord!Abstraction is about security and design. It allows a lead architect to set the rules ("Every payment method must have a process() method") without worrying about how the junior developers write the specific code for Credit Cards vs. PayPal. It ensures that the system fits together perfectly.