🧠 Java Quiz

Java Abstraction

Hide implementation details. Expose only what callers need.

The idea

Abstraction means defining what something does without specifying how. Java has two tools for this: abstract classes and interfaces.

Abstract classes

A class marked abstract cannot be instantiated directly — it's meant to be extended. It can mix concrete methods (with bodies) and abstract ones (no body).

Abstract class
abstract class Vehicle {
    String brand;

    public Vehicle(String brand) {
        this.brand = brand;
    }

    // Concrete method — shared by all subclasses
    public void describe() {
        System.out.println("This is a " + brand);
    }

    // Abstract — must be implemented by subclasses
    public abstract void start();
}

class Car extends Vehicle {
    public Car(String brand) { super(brand); }

    @Override
    public void start() {
        System.out.println("Engine vroom!");
    }
}

// new Vehicle("X");  // ERROR: cannot instantiate abstract class
Vehicle v = new Car("Tesla");
v.describe();
v.start();

Interfaces

An interface is a pure contract — a list of method signatures with no implementation (mostly). A class implements an interface, promising to provide the listed methods.

Interface
interface Drawable {
    void draw();
    double area();
}

class Circle implements Drawable {
    double r;
    public Circle(double r) { this.r = r; }

    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
    @Override
    public double area() {
        return Math.PI * r * r;
    }
}

Multiple interfaces

A class can extend only one class but implement multiple interfaces:

Multiple interfaces
interface Drivable { void drive(); }
interface Flyable  { void fly(); }

class FlyingCar implements Drivable, Flyable {
    @Override public void drive() { System.out.println("Driving..."); }
    @Override public void fly()   { System.out.println("Flying...");  }
}

Default methods (Java 8+)

Interfaces can include method bodies via default — useful for adding methods to existing interfaces without breaking implementers.

default method
interface Greeter {
    String getName();

    default void greet() {
        System.out.println("Hello, " + getName());
    }
}

Abstract class vs interface — when to use what?

SituationUse
You want shared code + state in subclassesAbstract class
You want to define a capability multiple unrelated classes can opt intoInterface
You need multiple inheritance of behaviorInterfaces
You want a strict template method patternAbstract class

Modern rule of thumb: prefer interfaces. Use abstract classes only when you have meaningful shared state to put in them.