Courses/Java/Interfaces & Abstract Classes

    Lesson 11 โ€ข Expert

    Interfaces & Abstract Classes

    Define contracts and partial blueprints โ€” the tools that make Java code truly flexible and testable in professional applications.

    ๐Ÿ“š Before You Start

    Make sure you're comfortable with these concepts from earlier lessons:

    • Classes & Objects (Lesson 9) โ€” creating and using classes
    • Inheritance (Lesson 10) โ€” extending classes with extends
    • Methods (Lesson 6) โ€” defining and calling methods

    What You'll Learn

    • โœ… What interfaces are โ€” contracts your classes promise to fulfill
    • โœ… Implementing interfaces with implements
    • โœ… Abstract classes โ€” partial blueprints with shared code
    • โœ… Default and static methods in interfaces (Java 8+)
    • โœ… Multiple interface implementation (Java's answer to multiple inheritance)
    • โœ… When to choose abstract classes vs interfaces (with clear rules)

    1๏ธโƒฃ What Are Interfaces?

    Real-world analogy: An interface is like a job description. It lists what the employee must be able to do (methods) โ€” "must be able to write reports, attend meetings, meet deadlines" โ€” but doesn't specify how they do it. Different employees (classes) fulfill the same job description in their own way.

    Why interfaces matter: They allow you to write code that works with any implementation. A sorting function that accepts Comparable works with Strings, Integers, custom objects โ€” anything that implements the interface.

    // Define the contract
    interface Drivable {
        void drive();       // what must be done
        void stop();        // no implementation โ€” just the signature
        int getSpeed();
    }
    
    // Fulfill the contract โ€” must implement ALL methods
    class Car implements Drivable {
        private int speed = 0;
        public void drive() { speed = 60; System.out.println("Car driving"); }
        public void stop()  { speed = 0;  System.out.println("Car stopped"); }
        public int getSpeed() { return speed; }
    }
    
    class Bicycle implements Drivable {
        private int speed = 0;
        public void drive() { speed = 15; System.out.println("Pedaling"); }
        public void stop()  { speed = 0;  System.out.println("Braking"); }
        public int getSpeed() { return speed; }
    }
    
    // Now any method accepting Drivable works with both!
    void testDrive(Drivable vehicle) {
        vehicle.drive();
        System.out.println("Speed: " + vehicle.getSpeed());
        vehicle.stop();
    }

    2๏ธโƒฃ Abstract Classes โ€” Partial Blueprints

    Analogy: An abstract class is like a partially built house. The foundation and framing are done (concrete methods), but you need to choose the paint color and flooring (abstract methods). You can't move into a half-built house (can't instantiate), but it gives every finished house a common structure.

    abstract class Shape {
        String color;      // shared field
    
        Shape(String color) { this.color = color; }
    
        abstract double area();   // MUST be implemented by children
    
        void describe() {         // shared implementation โ€” all shapes get this
            System.out.println(color + " shape, area = " + 
                               String.format("%.2f", area()));
        }
    }
    
    class Circle extends Shape {
        double radius;
        Circle(String color, double r) { super(color); radius = r; }
        double area() { return Math.PI * radius * radius; }
    }
    
    class Rectangle extends Shape {
        double w, h;
        Rectangle(String color, double w, double h) { super(color); this.w = w; this.h = h; }
        double area() { return w * h; }
    }
    
    // Shape s = new Shape("Red");  // ERROR! Can't instantiate abstract class
    Shape s = new Circle("Red", 5);
    s.describe(); // "Red shape, area = 78.54" โ€” polymorphism works!

    Try It: Interfaces & Polymorphism

    See how different classes implement the same interface contract

    Try it Yourself ยป
    JavaScript
    // ๐Ÿ’ก Try modifying this code and see what happens!
    // Java Interfaces & Polymorphism (Simulated)
    console.log("=== Interfaces & Polymorphism ===\n");
    
    // Interface simulation โ€” Drivable contract
    console.log("--- Interface: Drivable Contract ---");
    class Car {
        #speed = 0;
        drive() { this.#speed = 60; return "Car driving at " + this.#speed + " mph"; }
        stop()  { this.#speed = 0;  return "Car stopped"; }
        getSpeed() { return this.#speed; }
    }
    
    class Bicycle {
        #speed = 0;
        drive()
    ...

    3๏ธโƒฃ Multiple Interfaces & Default Methods

    Java doesn't allow multiple inheritance (extending two classes), but a class can implement multiple interfaces. Since Java 8, interfaces can also have default methods with implementations:

    interface Flyable {
        void fly();
        default void land() { System.out.println("Landing safely"); }
    }
    
    interface Swimmable {
        void swim();
        default void dive() { System.out.println("Diving deep"); }
    }
    
    // A Duck can do both!
    class Duck implements Flyable, Swimmable {
        public void fly()  { System.out.println("Duck flies"); }
        public void swim() { System.out.println("Duck swims"); }
        // Inherits default land() and dive() for free!
    }
    
    Duck d = new Duck();
    d.fly();   d.land();   // from Flyable
    d.swim();  d.dive();   // from Swimmable

    4๏ธโƒฃ Interface vs Abstract Class โ€” Decision Guide

    FeatureInterfaceAbstract Class
    MethodsAbstract + defaultAbstract + concrete
    FieldsConstants onlyAny fields
    Multipleโœ… Implement manyโŒ Extend one
    ConstructorโŒ Noneโœ… Yes
    When to useUnrelated classes share behaviorRelated classes share code

    Simple rule: Start with an interface. Only switch to abstract class when you need shared state (fields) or constructors.

    Try It: Abstract Class Shape Hierarchy

    Build a shape system with abstract classes and polymorphism

    Try it Yourself ยป
    JavaScript
    // ๐Ÿ’ก Try modifying this code and see what happens!
    // Abstract Class Shape Hierarchy (Simulated)
    console.log("=== Abstract Class Hierarchy ===\n");
    
    class Shape {
        constructor(color) {
            this.color = color;
            if (new.target === Shape) throw new Error("Can't instantiate abstract class!");
        }
        area() { throw new Error("Must implement area()!"); }
        perimeter() { throw new Error("Must implement perimeter()!"); }
        describe() {
            return this.color + " " + this.constru
    ...

    5๏ธโƒฃ Real-World Interface Examples

    Comparable<T> โ€” lets objects be sorted: Collections.sort(list)

    Serializable โ€” marks objects that can be saved to files or sent over network

    Iterable<T> โ€” allows objects to work in for-each loops

    Runnable โ€” defines code that can run in a thread

    Every Java framework you'll ever use โ€” Spring, Android, Jakarta EE โ€” is built on interfaces. Learning them well now pays off enormously later.

    6๏ธโƒฃ Common Beginner Mistakes

    โŒ Mistake 1: Using abstract class when interface would suffice

    If there's no shared state or code, use an interface. It's more flexible โ€” classes can implement many interfaces but only extend one class.

    โŒ Mistake 2: Forgetting to implement ALL interface methods

    If your class says implements Drivable, it must provide implementations for every abstract method โ€” or itself be declared abstract.

    โŒ Mistake 3: Not making interface methods public

    Interface methods are implicitly public abstract. When you implement them, you must declare them public โ€” a lower access modifier won't compile.

    Try It: Payment System with Interfaces

    Build a real-world payment processing system using interface contracts

    Try it Yourself ยป
    JavaScript
    // ๐Ÿ’ก Try modifying this code and see what happens!
    // Practical Payment System (Simulated)
    console.log("=== Payment System with Interfaces ===\n");
    
    // Multiple interfaces โ€” Payable + Refundable
    class CreditCard {
        constructor(number) { this.number = "****" + number.slice(-4); }
        pay(amount) { return "๐Ÿ’ณ Charged $" + amount.toFixed(2) + " to card " + this.number; }
        refund(amount) { return "โ†ฉ๏ธ Refunded $" + amount.toFixed(2) + " to card " + this.number; }
    }
    
    class PayPal {
        construc
    ...

    ๐Ÿ“‹ Quick Reference

    KeywordSyntaxPurpose
    interfaceinterface Drivable { }Define contract
    implementsclass Car implements DrivableFulfill contract
    abstract classabstract class ShapePartial blueprint
    abstract methodabstract double area();Must be implemented
    defaultdefault void log() { }Interface default method
    multi-implimplements A, B, CMultiple interfaces

    ๐ŸŽ‰ Lesson Complete!

    You now understand interfaces, abstract classes, default methods, and when to use each โ€” essential tools for designing flexible, maintainable Java systems that can evolve over time.

    Next up: Exception Handling โ€” handle errors gracefully with try-catch and never let your program crash unexpectedly.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service