A class can only extend one parent. But a Dog can be both an Animal and a Pet. Interfaces define contracts - a class can implement multiple interfaces, promising to provide certain methods without inheriting implementation.

Basic interface

Define a contract that classes must fulfill.

example
BasicInterface.java
Replay: real traced execution (multi-file project)
// Basic Interface Declaration and Implementation

public class BasicInterface {
    public static void main(String[] args) {
        System.out.println("=== Basic Interface ===\n");

        // Cannot instantiate interface!
        // Drawable d = new Drawable();  // ERROR

        // Create implementing classes
        double circleRadius = 5;
        double rectangleWidth = 4;
        Circle circle = new Circle(circleRadius);
        Rectangle rectangle = new Rectangle(rectangleWidth, 6);

        // Call interface methods
        circle.draw();
        rectangle.draw();

        System.out.println("\n=== Interface as Type ===");

        // Use interface type for reference
        Drawable shape1 = new Circle(3);
        Drawable shape2 = new Rectangle(2, 5);

        shape1.draw();
        shape2.draw();

        System.out.println("\n=== Array of Interface Type ===");

        Drawable[] shapes = {
            new Circle(1),
            new Rectangle(2, 3),
            new Circle(4)
        };

        for (Drawable shape : shapes) {
            shape.draw();
        }

        System.out.println("\n=== Interface Characteristics ===");
        System.out.println("""
        Interface:
        - Cannot be instantiated
        - Methods are public abstract by default
        - Fields are public static final (constants)
        - Classes use 'implements' keyword
        - Implementing class MUST provide all methods
        """);
    }
}

// Interface declaration
interface Drawable {
    // Method declaration - implicitly public abstract
    void draw();

    // Can have multiple methods
    void resize(double factor);

    // Constants - implicitly public static final
    int DEFAULT_SIZE = 10;
}

// Class implements interface
class Circle implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // MUST implement all interface methods
    @Override
    public void draw() {
        System.out.println("Drawing circle with radius " + radius);
    }

    @Override
    public void resize(double factor) {
        radius *= factor;
        System.out.println("Circle resized to radius " + radius);
    }
}

class Rectangle implements Drawable {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Drawing rectangle " + width + " x " + height);
    }

    @Override
    public void resize(double factor) {
        width *= factor;
        height *= factor;
        System.out.println("Rectangle resized to " + width + " x " + height);
    }
}

// Basic Interface Declaration and Implementation

public class BasicInterface {
    public static void main(String[] args) {
        System.out.println("=== Basic Interface ===\n");

        // Cannot instantiate interface!
        // Drawable d = new Drawable();  // ERROR

        // Create implementing classes
        double circleRadius = 2;
        double rectangleWidth = 4;
        Circle circle = new Circle(circleRadius);
        Rectangle rectangle = new Rectangle(rectangleWidth, 6);

        // Call interface methods
        circle.draw();
        rectangle.draw();

        System.out.println("\n=== Interface as Type ===");

        // Use interface type for reference
        Drawable shape1 = new Circle(3);
        Drawable shape2 = new Rectangle(2, 5);

        shape1.draw();
        shape2.draw();

        System.out.println("\n=== Array of Interface Type ===");

        Drawable[] shapes = {
            new Circle(1),
            new Rectangle(2, 3),
            new Circle(4)
        };

        for (Drawable shape : shapes) {
            shape.draw();
        }

        System.out.println("\n=== Interface Characteristics ===");
        System.out.println("""
        Interface:
        - Cannot be instantiated
        - Methods are public abstract by default
        - Fields are public static final (constants)
        - Classes use 'implements' keyword
        - Implementing class MUST provide all methods
        """);
    }
}

// Interface declaration
interface Drawable {
    // Method declaration - implicitly public abstract
    void draw();

    // Can have multiple methods
    void resize(double factor);

    // Constants - implicitly public static final
    int DEFAULT_SIZE = 10;
}

// Class implements interface
class Circle implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // MUST implement all interface methods
    @Override
    public void draw() {
        System.out.println("Drawing circle with radius " + radius);
    }

    @Override
    public void resize(double factor) {
        radius *= factor;
        System.out.println("Circle resized to radius " + radius);
    }
}

class Rectangle implements Drawable {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Drawing rectangle " + width + " x " + height);
    }

    @Override
    public void resize(double factor) {
        width *= factor;
        height *= factor;
        System.out.println("Rectangle resized to " + width + " x " + height);
    }
}

// Basic Interface Declaration and Implementation

public class BasicInterface {
    public static void main(String[] args) {
        System.out.println("=== Basic Interface ===\n");

        // Cannot instantiate interface!
        // Drawable d = new Drawable();  // ERROR

        // Create implementing classes
        double circleRadius = 8;
        double rectangleWidth = 4;
        Circle circle = new Circle(circleRadius);
        Rectangle rectangle = new Rectangle(rectangleWidth, 6);

        // Call interface methods
        circle.draw();
        rectangle.draw();

        System.out.println("\n=== Interface as Type ===");

        // Use interface type for reference
        Drawable shape1 = new Circle(3);
        Drawable shape2 = new Rectangle(2, 5);

        shape1.draw();
        shape2.draw();

        System.out.println("\n=== Array of Interface Type ===");

        Drawable[] shapes = {
            new Circle(1),
            new Rectangle(2, 3),
            new Circle(4)
        };

        for (Drawable shape : shapes) {
            shape.draw();
        }

        System.out.println("\n=== Interface Characteristics ===");
        System.out.println("""
        Interface:
        - Cannot be instantiated
        - Methods are public abstract by default
        - Fields are public static final (constants)
        - Classes use 'implements' keyword
        - Implementing class MUST provide all methods
        """);
    }
}

// Interface declaration
interface Drawable {
    // Method declaration - implicitly public abstract
    void draw();

    // Can have multiple methods
    void resize(double factor);

    // Constants - implicitly public static final
    int DEFAULT_SIZE = 10;
}

// Class implements interface
class Circle implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // MUST implement all interface methods
    @Override
    public void draw() {
        System.out.println("Drawing circle with radius " + radius);
    }

    @Override
    public void resize(double factor) {
        radius *= factor;
        System.out.println("Circle resized to radius " + radius);
    }
}

class Rectangle implements Drawable {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Drawing rectangle " + width + " x " + height);
    }

    @Override
    public void resize(double factor) {
        width *= factor;
        height *= factor;
        System.out.println("Rectangle resized to " + width + " x " + height);
    }
}

// Basic Interface Declaration and Implementation

public class BasicInterface {
    public static void main(String[] args) {
        System.out.println("=== Basic Interface ===\n");

        // Cannot instantiate interface!
        // Drawable d = new Drawable();  // ERROR

        // Create implementing classes
        double circleRadius = 5;
        double rectangleWidth = 3;
        Circle circle = new Circle(circleRadius);
        Rectangle rectangle = new Rectangle(rectangleWidth, 6);

        // Call interface methods
        circle.draw();
        rectangle.draw();

        System.out.println("\n=== Interface as Type ===");

        // Use interface type for reference
        Drawable shape1 = new Circle(3);
        Drawable shape2 = new Rectangle(2, 5);

        shape1.draw();
        shape2.draw();

        System.out.println("\n=== Array of Interface Type ===");

        Drawable[] shapes = {
            new Circle(1),
            new Rectangle(2, 3),
            new Circle(4)
        };

        for (Drawable shape : shapes) {
            shape.draw();
        }

        System.out.println("\n=== Interface Characteristics ===");
        System.out.println("""
        Interface:
        - Cannot be instantiated
        - Methods are public abstract by default
        - Fields are public static final (constants)
        - Classes use 'implements' keyword
        - Implementing class MUST provide all methods
        """);
    }
}

// Interface declaration
interface Drawable {
    // Method declaration - implicitly public abstract
    void draw();

    // Can have multiple methods
    void resize(double factor);

    // Constants - implicitly public static final
    int DEFAULT_SIZE = 10;
}

// Class implements interface
class Circle implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // MUST implement all interface methods
    @Override
    public void draw() {
        System.out.println("Drawing circle with radius " + radius);
    }

    @Override
    public void resize(double factor) {
        radius *= factor;
        System.out.println("Circle resized to radius " + radius);
    }
}

class Rectangle implements Drawable {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Drawing rectangle " + width + " x " + height);
    }

    @Override
    public void resize(double factor) {
        width *= factor;
        height *= factor;
        System.out.println("Rectangle resized to " + width + " x " + height);
    }
}

// Basic Interface Declaration and Implementation

public class BasicInterface {
    public static void main(String[] args) {
        System.out.println("=== Basic Interface ===\n");

        // Cannot instantiate interface!
        // Drawable d = new Drawable();  // ERROR

        // Create implementing classes
        double circleRadius = 5;
        double rectangleWidth = 7;
        Circle circle = new Circle(circleRadius);
        Rectangle rectangle = new Rectangle(rectangleWidth, 6);

        // Call interface methods
        circle.draw();
        rectangle.draw();

        System.out.println("\n=== Interface as Type ===");

        // Use interface type for reference
        Drawable shape1 = new Circle(3);
        Drawable shape2 = new Rectangle(2, 5);

        shape1.draw();
        shape2.draw();

        System.out.println("\n=== Array of Interface Type ===");

        Drawable[] shapes = {
            new Circle(1),
            new Rectangle(2, 3),
            new Circle(4)
        };

        for (Drawable shape : shapes) {
            shape.draw();
        }

        System.out.println("\n=== Interface Characteristics ===");
        System.out.println("""
        Interface:
        - Cannot be instantiated
        - Methods are public abstract by default
        - Fields are public static final (constants)
        - Classes use 'implements' keyword
        - Implementing class MUST provide all methods
        """);
    }
}

// Interface declaration
interface Drawable {
    // Method declaration - implicitly public abstract
    void draw();

    // Can have multiple methods
    void resize(double factor);

    // Constants - implicitly public static final
    int DEFAULT_SIZE = 10;
}

// Class implements interface
class Circle implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    // MUST implement all interface methods
    @Override
    public void draw() {
        System.out.println("Drawing circle with radius " + radius);
    }

    @Override
    public void resize(double factor) {
        radius *= factor;
        System.out.println("Circle resized to radius " + radius);
    }
}

class Rectangle implements Drawable {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println("Drawing rectangle " + width + " x " + height);
    }

    @Override
    public void resize(double factor) {
        width *= factor;
        height *= factor;
        System.out.println("Rectangle resized to " + width + " x " + height);
    }
}

  1. circleRadius ← 5.0, rectangleWidth ← 4.0

    3public class BasicInterface {4    public static void main(String[] args) {5        System.out.println("=== Basic Interface ===\n");6        7        // Cannot instantiate interface!  //?noinstantiate8        // Drawable d = new Drawable();  // ERROR9        10        // Create implementing classes  //?createimpl11        double circleRadius→ 5.0 = 5;  //@circleRadius=2, 812        double rectangleWidth→ 4.0 = 4;  //@rectangleWidth=3, 713        Circle circle = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);
    output=== Basic Interface ===
  2. this.radius ← 5.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    12        double rectangleWidth = 4;  //@rectangleWidth=3, 713        Circle circle→ ⟨Circle A⟩ = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods  //?callmethods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference  //?interfacetype23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {  //?interfacearray32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();  //?polymorphism39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration  //?interfacedecl54interface Drawable {55    // Method declaration - implicitly public abstract  //?methoddecl56    void draw();  //?implicitpublic57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final  //?constant62    int DEFAULT_SIZE = 10;  //?implicitfinal63}6465// Class implements interface  //?classimpl66class Circle implements Drawable {  //?implements67    private double radius;68    69    Circle(double radius5.0) {70        this.radius→ 5.0 = radius5.0;71    }
    All 4 passes — pass 1 is the card above
    passradiusthis.radiuscircleshape1
    15.05.0⟨Circle A⟩
    23.03.0⟨Circle B⟩
    31.01.0
    44.04.0
  3. this.width ← 4.0, this.height ← 6.0, rectangle ← ⟨Rectangle C⟩

    pass 1 of 3
    13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle→ ⟨Rectangle C⟩ = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods  //?callmethods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference  //?interfacetype23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {  //?interfacearray32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();  //?polymorphism39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration  //?interfacedecl54interface Drawable {55    // Method declaration - implicitly public abstract  //?methoddecl56    void draw();  //?implicitpublic57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final  //?constant62    int DEFAULT_SIZE = 10;  //?implicitfinal63}6465// Class implements interface  //?classimpl66class Circle implements Drawable {  //?implements67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods  //?mustimplement74    @Override75    public void draw() {  //?publicrequired76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width4.0, double height6.0) {90        this.width→ 4.0 = width4.0;91        this.height→ 6.0 = height6.0;92    }
    All 3 passes — pass 1 is the card above
    passwidthheightthis.widththis.heightrectangleshape2
    14.06.04.06.0⟨Rectangle C⟩
    22.05.02.05.0⟨Rectangle D⟩
    32.03.02.03.0
  4. @Override public void draw()

    pass 1 of 4
    16        // Call interface methods  //?callmethods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference  //?interfacetype23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {  //?interfacearray32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();  //?polymorphism39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration  //?interfacedecl54interface Drawable {55    // Method declaration - implicitly public abstract  //?methoddecl56    void draw();  //?implicitpublic57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final  //?constant62    int DEFAULT_SIZE = 10;  //?implicitfinal63}6465// Class implements interface  //?classimpl66class Circle implements Drawable {  //?implements67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods  //?mustimplement74    @Override75    public void draw() {  //?publicrequired76        System.out.println("Drawing circle with radius " + radius5.0);77    }
    outputDrawing circle with radius 5.0
    All 4 passes — pass 1 is the card above
    passradius
    15.0
    23.0
    31.0
    44.0
  5. @Override public void draw()

    pass 1 of 3
    17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference  //?interfacetype23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {  //?interfacearray32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();  //?polymorphism39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration  //?interfacedecl54interface Drawable {55    // Method declaration - implicitly public abstract  //?methoddecl56    void draw();  //?implicitpublic57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final  //?constant62    int DEFAULT_SIZE = 10;  //?implicitfinal63}6465// Class implements interface  //?classimpl66class Circle implements Drawable {  //?implements67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods  //?mustimplement74    @Override75    public void draw() {  //?publicrequired76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width, double height) {90        this.width = width;91        this.height = height;92    }93    94    @Override95    public void draw() {96        System.out.println("Drawing rectangle " + width4.0 + " x " + height6.0);97    }
    outputDrawing rectangle 4.0 x 6.0
    
    === Interface as Type ===
    All 3 passes — pass 1 is the card above
    passwidthheight
    14.06.0
    22.05.0
    32.03.0
  6. for (Drawable shape : shapes)

    pass 1 of 3
    37for (Drawable shape⟨Circle E⟩ : shapes) {38    shape.draw();  //?polymorphism39}
    All 3 passes — pass 1 is the card above
    passshape
    1⟨Circle E⟩
    2⟨Rectangle F⟩
    3⟨Circle G⟩
  1. circleRadius ← 2.0, rectangleWidth ← 4.0

    3public class BasicInterface {4    public static void main(String[] args) {5        System.out.println("=== Basic Interface ===\n");6        7        // Cannot instantiate interface!8        // Drawable d = new Drawable();  // ERROR9        10        // Create implementing classes11        double circleRadius→ 2.0 = 2;12        double rectangleWidth→ 4.0 = 4;13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);
    output=== Basic Interface ===
  2. this.radius ← 2.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    12        double rectangleWidth = 4;13        Circle circle→ ⟨Circle A⟩ = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius2.0) {70        this.radius→ 2.0 = radius2.0;71    }
    All 4 passes — pass 1 is the card above
    passradiusthis.radiuscircleshape1
    12.02.0⟨Circle A⟩
    23.03.0⟨Circle B⟩
    31.01.0
    44.04.0
  3. this.width ← 4.0, this.height ← 6.0, rectangle ← ⟨Rectangle C⟩

    pass 1 of 3
    13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle→ ⟨Rectangle C⟩ = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width4.0, double height6.0) {90        this.width→ 4.0 = width4.0;91        this.height→ 6.0 = height6.0;92    }
    All 3 passes — pass 1 is the card above
    passwidthheightthis.widththis.heightrectangleshape2
    14.06.04.06.0⟨Rectangle C⟩
    22.05.02.05.0⟨Rectangle D⟩
    32.03.02.03.0
  4. @Override public void draw()

    pass 1 of 4
    16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius2.0);77    }
    outputDrawing circle with radius 2.0
    All 4 passes — pass 1 is the card above
    passradius
    12.0
    23.0
    31.0
    44.0
  5. @Override public void draw()

    pass 1 of 3
    17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width, double height) {90        this.width = width;91        this.height = height;92    }93    94    @Override95    public void draw() {96        System.out.println("Drawing rectangle " + width4.0 + " x " + height6.0);97    }
    outputDrawing rectangle 4.0 x 6.0
    
    === Interface as Type ===
    All 3 passes — pass 1 is the card above
    passwidthheight
    14.06.0
    22.05.0
    32.03.0
  6. for (Drawable shape : shapes)

    pass 1 of 3
    37for (Drawable shape⟨Circle E⟩ : shapes) {38    shape.draw();39}
    All 3 passes — pass 1 is the card above
    passshape
    1⟨Circle E⟩
    2⟨Rectangle F⟩
    3⟨Circle G⟩
  1. circleRadius ← 8.0, rectangleWidth ← 4.0

    3public class BasicInterface {4    public static void main(String[] args) {5        System.out.println("=== Basic Interface ===\n");6        7        // Cannot instantiate interface!8        // Drawable d = new Drawable();  // ERROR9        10        // Create implementing classes11        double circleRadius→ 8.0 = 8;12        double rectangleWidth→ 4.0 = 4;13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);
    output=== Basic Interface ===
  2. this.radius ← 8.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    12        double rectangleWidth = 4;13        Circle circle→ ⟨Circle A⟩ = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius8.0) {70        this.radius→ 8.0 = radius8.0;71    }
    All 4 passes — pass 1 is the card above
    passradiusthis.radiuscircleshape1
    18.08.0⟨Circle A⟩
    23.03.0⟨Circle B⟩
    31.01.0
    44.04.0
  3. this.width ← 4.0, this.height ← 6.0, rectangle ← ⟨Rectangle C⟩

    pass 1 of 3
    13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle→ ⟨Rectangle C⟩ = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width4.0, double height6.0) {90        this.width→ 4.0 = width4.0;91        this.height→ 6.0 = height6.0;92    }
    All 3 passes — pass 1 is the card above
    passwidthheightthis.widththis.heightrectangleshape2
    14.06.04.06.0⟨Rectangle C⟩
    22.05.02.05.0⟨Rectangle D⟩
    32.03.02.03.0
  4. @Override public void draw()

    pass 1 of 4
    16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius8.0);77    }
    outputDrawing circle with radius 8.0
    All 4 passes — pass 1 is the card above
    passradius
    18.0
    23.0
    31.0
    44.0
  5. @Override public void draw()

    pass 1 of 3
    17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width, double height) {90        this.width = width;91        this.height = height;92    }93    94    @Override95    public void draw() {96        System.out.println("Drawing rectangle " + width4.0 + " x " + height6.0);97    }
    outputDrawing rectangle 4.0 x 6.0
    
    === Interface as Type ===
    All 3 passes — pass 1 is the card above
    passwidthheight
    14.06.0
    22.05.0
    32.03.0
  6. for (Drawable shape : shapes)

    pass 1 of 3
    37for (Drawable shape⟨Circle E⟩ : shapes) {38    shape.draw();39}
    All 3 passes — pass 1 is the card above
    passshape
    1⟨Circle E⟩
    2⟨Rectangle F⟩
    3⟨Circle G⟩
  1. circleRadius ← 5.0, rectangleWidth ← 3.0

    3public class BasicInterface {4    public static void main(String[] args) {5        System.out.println("=== Basic Interface ===\n");6        7        // Cannot instantiate interface!8        // Drawable d = new Drawable();  // ERROR9        10        // Create implementing classes11        double circleRadius→ 5.0 = 5;12        double rectangleWidth→ 3.0 = 3;13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);
    output=== Basic Interface ===
  2. this.radius ← 5.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    12        double rectangleWidth = 3;13        Circle circle→ ⟨Circle A⟩ = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius5.0) {70        this.radius→ 5.0 = radius5.0;71    }
    All 4 passes — pass 1 is the card above
    passradiusthis.radiuscircleshape1
    15.05.0⟨Circle A⟩
    23.03.0⟨Circle B⟩
    31.01.0
    44.04.0
  3. this.width ← 3.0, this.height ← 6.0, rectangle ← ⟨Rectangle C⟩

    pass 1 of 3
    13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle→ ⟨Rectangle C⟩ = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width3.0, double height6.0) {90        this.width→ 3.0 = width3.0;91        this.height→ 6.0 = height6.0;92    }
    All 3 passes — pass 1 is the card above
    passwidthheightthis.widththis.heightrectangleshape2
    13.06.03.06.0⟨Rectangle C⟩
    22.05.02.05.0⟨Rectangle D⟩
    32.03.02.03.0
  4. @Override public void draw()

    pass 1 of 4
    16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius5.0);77    }
    outputDrawing circle with radius 5.0
    All 4 passes — pass 1 is the card above
    passradius
    15.0
    23.0
    31.0
    44.0
  5. @Override public void draw()

    pass 1 of 3
    17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width, double height) {90        this.width = width;91        this.height = height;92    }93    94    @Override95    public void draw() {96        System.out.println("Drawing rectangle " + width3.0 + " x " + height6.0);97    }
    outputDrawing rectangle 3.0 x 6.0
    
    === Interface as Type ===
    All 3 passes — pass 1 is the card above
    passwidthheight
    13.06.0
    22.05.0
    32.03.0
  6. for (Drawable shape : shapes)

    pass 1 of 3
    37for (Drawable shape⟨Circle E⟩ : shapes) {38    shape.draw();39}
    All 3 passes — pass 1 is the card above
    passshape
    1⟨Circle E⟩
    2⟨Rectangle F⟩
    3⟨Circle G⟩
  1. circleRadius ← 5.0, rectangleWidth ← 7.0

    3public class BasicInterface {4    public static void main(String[] args) {5        System.out.println("=== Basic Interface ===\n");6        7        // Cannot instantiate interface!8        // Drawable d = new Drawable();  // ERROR9        10        // Create implementing classes11        double circleRadius→ 5.0 = 5;12        double rectangleWidth→ 7.0 = 7;13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);
    output=== Basic Interface ===
  2. this.radius ← 5.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    12        double rectangleWidth = 7;13        Circle circle→ ⟨Circle A⟩ = new Circle(circleRadius);14        Rectangle rectangle = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius5.0) {70        this.radius→ 5.0 = radius5.0;71    }
    All 4 passes — pass 1 is the card above
    passradiusthis.radiuscircleshape1
    15.05.0⟨Circle A⟩
    23.03.0⟨Circle B⟩
    31.01.0
    44.04.0
  3. this.width ← 7.0, this.height ← 6.0, rectangle ← ⟨Rectangle C⟩

    pass 1 of 3
    13        Circle circle = new Circle(circleRadius);14        Rectangle rectangle→ ⟨Rectangle C⟩ = new Rectangle(rectangleWidth, 6);15        16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width7.0, double height6.0) {90        this.width→ 7.0 = width7.0;91        this.height→ 6.0 = height6.0;92    }
    All 3 passes — pass 1 is the card above
    passwidthheightthis.widththis.heightrectangleshape2
    17.06.07.06.0⟨Rectangle C⟩
    22.05.02.05.0⟨Rectangle D⟩
    32.03.02.03.0
  4. @Override public void draw()

    pass 1 of 4
    16        // Call interface methods17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius5.0);77    }
    outputDrawing circle with radius 5.0
    All 4 passes — pass 1 is the card above
    passradius
    15.0
    23.0
    31.0
    44.0
  5. @Override public void draw()

    pass 1 of 3
    17        circle.draw();18        rectangle.draw();19        20        System.out.println("\n=== Interface as Type ===");21        22        // Use interface type for reference23        Drawable shape1 = new Circle(3);24        Drawable shape2 = new Rectangle(2, 5);25        26        shape1.draw();27        shape2.draw();28        29        System.out.println("\n=== Array of Interface Type ===");30        31        Drawable[] shapes = {32            new Circle(1),33            new Rectangle(2, 3),34            new Circle(4)35        };36        37        for (Drawable shape : shapes) {38            shape.draw();39        }40        41        System.out.println("\n=== Interface Characteristics ===");42        System.out.println("""43        Interface:44        - Cannot be instantiated45        - Methods are public abstract by default46        - Fields are public static final (constants)47        - Classes use 'implements' keyword48        - Implementing class MUST provide all methods49        """);50    }51}5253// Interface declaration54interface Drawable {55    // Method declaration - implicitly public abstract56    void draw();57    58    // Can have multiple methods59    void resize(double factor);60    61    // Constants - implicitly public static final62    int DEFAULT_SIZE = 10;63}6465// Class implements interface66class Circle implements Drawable {67    private double radius;68    69    Circle(double radius) {70        this.radius = radius;71    }72    73    // MUST implement all interface methods74    @Override75    public void draw() {76        System.out.println("Drawing circle with radius " + radius);77    }78    79    @Override80    public void resize(double factor) {81        radius *= factor;82        System.out.println("Circle resized to radius " + radius);83    }84}8586class Rectangle implements Drawable {87    private double width, height;88    89    Rectangle(double width, double height) {90        this.width = width;91        this.height = height;92    }93    94    @Override95    public void draw() {96        System.out.println("Drawing rectangle " + width7.0 + " x " + height6.0);97    }
    outputDrawing rectangle 7.0 x 6.0
    
    === Interface as Type ===
    All 3 passes — pass 1 is the card above
    passwidthheight
    17.06.0
    22.05.0
    32.03.0
  6. for (Drawable shape : shapes)

    pass 1 of 3
    37for (Drawable shape⟨Circle E⟩ : shapes) {38    shape.draw();39}
    All 3 passes — pass 1 is the card above
    passshape
    1⟨Circle E⟩
    2⟨Rectangle F⟩
    3⟨Circle G⟩

interface defines method signatures. No implementation (pre-Java 8).

interface Contract of methods a class must implement. All methods implicitly public abstract.

Implement multiple interfaces

A class can implement many interfaces.

MultipleInterfaces.java
Replay: real traced execution (multi-file project)
// Implementing Multiple Interfaces

public class MultipleInterfaces {
    public static void main(String[] args) {
        System.out.println("=== Multiple Interfaces ===\n");

        // SmartPhone implements multiple interfaces
        SmartPhone phone = new SmartPhone("iPhone 15");

        System.out.println("--- Using as Camera ---");
        phone.takePhoto();
        phone.recordVideo();

        System.out.println("\n--- Using as Phone ---");
        phone.makeCall("555-1234");
        phone.sendText("Hello!");

        System.out.println("\n--- Using as MediaPlayer ---");
        phone.playMusic("Bohemian Rhapsody");
        phone.playVideo("YouTube clip");

        System.out.println("\n=== Interface References ===");

        // Same object, different interface views
        Camera cam = phone;
        Callable call = phone;
        MediaPlayer player = phone;

        cam.takePhoto();          // Only Camera methods visible
        call.makeCall("555-5678");
        player.playMusic("Song");

        System.out.println("\n=== Duck Typing with Interfaces ===");

        // Different devices, same interfaces
        Camera[] cameras = {
            new SmartPhone("Pixel"),
            new DigitalCamera("Canon"),
        };

        for (Camera c : cameras) {
            c.takePhoto();
        }
    }
}

// Interface 1
interface Camera {
    void takePhoto();
    void recordVideo();
}

// Interface 2
interface Callable {
    void makeCall(String number);
    void sendText(String message);
}

// Interface 3
interface MediaPlayer {
    void playMusic(String song);
    void playVideo(String video);
}

// Class implementing MULTIPLE interfaces
class SmartPhone implements Camera, Callable, MediaPlayer {
    private String model;

    SmartPhone(String model) {
        this.model = model;
    }

    // From Camera
    @Override
    public void takePhoto() {
        System.out.println(model + ": 📷 Taking photo");
    }

    @Override
    public void recordVideo() {
        System.out.println(model + ": 🎥 Recording video");
    }

    // From Callable
    @Override
    public void makeCall(String number) {
        System.out.println(model + ": 📞 Calling " + number);
    }

    @Override
    public void sendText(String message) {
        System.out.println(model + ": 💬 Sending: " + message);
    }

    // From MediaPlayer
    @Override
    public void playMusic(String song) {
        System.out.println(model + ": 🎵 Playing " + song);
    }

    @Override
    public void playVideo(String video) {
        System.out.println(model + ": ▶️ Playing " + video);
    }
}

// Another class implementing just Camera
class DigitalCamera implements Camera {
    private String model;

    DigitalCamera(String model) {
        this.model = model;
    }

    @Override
    public void takePhoto() {
        System.out.println(model + " DSLR: 📷 High-quality photo");
    }

    @Override
    public void recordVideo() {
        System.out.println(model + " DSLR: 🎥 4K video recording");
    }
    // No need to implement Callable or MediaPlayer!
}

  1. public static void main(String[] args)

    3public class MultipleInterfaces {4    public static void main(String[] args) {5        System.out.println("=== Multiple Interfaces ===\n");6        7        // SmartPhone implements multiple interfaces  //?multiimpl8        SmartPhone phone = new SmartPhone("iPhone 15");
    output=== Multiple Interfaces ===
  2. this.model ← iPhone 15, phone ← ⟨SmartPhone A⟩

    pass 1 of 2
    7        // SmartPhone implements multiple interfaces  //?multiimpl8        SmartPhone phone→ ⟨SmartPhone A⟩ = new SmartPhone("iPhone 15");9        10        System.out.println("--- Using as Camera ---");11        phone.takePhoto();12        phone.recordVideo();13        14        System.out.println("\n--- Using as Phone ---");15        phone.makeCall("555-1234");16        phone.sendText("Hello!");17        18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String modeliPhone 15) {70        this.model→ iPhone 15 = modeliPhone 15;71    }
    output--- Using as Camera ---
  3. @Override public void takePhoto()

    pass 1 of 3
    10        System.out.println("--- Using as Camera ---");11        phone.takePhoto();12        phone.recordVideo();13        14        System.out.println("\n--- Using as Phone ---");15        phone.makeCall("555-1234");16        phone.sendText("Hello!");17        18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(modeliPhone 15 + ": 📷 Taking photo");77    }
    outputiPhone 15: 📷 Taking photo
    All 3 passes — pass 1 is the card above
    passmodelnumbermessagesongvideoccamcallplayerthis.model
    1iPhone 15555-1234Hello!Bohemian RhapsodyYouTube clip⟨SmartPhone A⟩⟨SmartPhone A⟩⟨SmartPhone A⟩
    2iPhone 15555-5678Song⟨SmartPhone B⟩Pixel
    3Pixel⟨DigitalCamera C⟩
  4. @Override public void recordVideo()

    11        phone.takePhoto();12        phone.recordVideo();13        14        System.out.println("\n--- Using as Phone ---");15        phone.makeCall("555-1234");16        phone.sendText("Hello!");17        18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(modeliPhone 15 + ": 🎥 Recording video");82    }
    outputiPhone 15: 🎥 Recording video
    
    --- Using as Phone ---
  5. @Override public void makeCall(String number)

    pass 1 of 2
    14        System.out.println("\n--- Using as Phone ---");15        phone.makeCall("555-1234");16        phone.sendText("Hello!");17        18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number555-1234) {87        System.out.println(modeliPhone 15 + ": 📞 Calling " + number555-1234);88    }
    outputiPhone 15: 📞 Calling 555-1234
  6. @Override public void sendText(String message)

    15        phone.makeCall("555-1234");16        phone.sendText("Hello!");17        18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String messageHello!) {92        System.out.println(modeliPhone 15 + ": 💬 Sending: " + messageHello!);93    }
    outputiPhone 15: 💬 Sending: Hello!
    
    --- Using as MediaPlayer ---
  7. @Override public void playMusic(String song)

    pass 1 of 2
    18        System.out.println("\n--- Using as MediaPlayer ---");19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam = phone;       //?ascamera26        Callable call = phone;    //?ascallable27        MediaPlayer player = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String message) {92        System.out.println(model + ": 💬 Sending: " + message);93    }94    95    // From MediaPlayer  //?mediaimpls96    @Override97    public void playMusic(String songBohemian Rhapsody) {98        System.out.println(modeliPhone 15 + ": 🎵 Playing " + songBohemian Rhapsody);99    }
    outputiPhone 15: 🎵 Playing Bohemian Rhapsody
  8. cam ← ⟨SmartPhone A⟩, call ← ⟨SmartPhone A⟩, player ← ⟨SmartPhone A⟩

    19        phone.playMusic("Bohemian Rhapsody");20        phone.playVideo("YouTube clip");21        22        System.out.println("\n=== Interface References ===");23        24        // Same object, different interface views  //?interfaceviews25        Camera cam→ ⟨SmartPhone A⟩ = phone;       //?ascamera26        Callable call→ ⟨SmartPhone A⟩ = phone;    //?ascallable27        MediaPlayer player→ ⟨SmartPhone A⟩ = phone;28        29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String message) {92        System.out.println(model + ": 💬 Sending: " + message);93    }94    95    // From MediaPlayer  //?mediaimpls96    @Override97    public void playMusic(String song) {98        System.out.println(model + ": 🎵 Playing " + song);99    }100    101    @Override102    public void playVideo(String videoYouTube clip) {103        System.out.println(modeliPhone 15 + ": ▶️ Playing " + videoYouTube clip);104    }
    outputiPhone 15: ▶️ Playing YouTube clip
    
    === Interface References ===
  9. @Override public void makeCall(String number)

    pass 2 of 2
    29        cam.takePhoto();          // Only Camera methods visible30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number555-5678) {87        System.out.println(modeliPhone 15 + ": 📞 Calling " + number555-5678);88    }
    outputiPhone 15: 📞 Calling 555-5678
  10. @Override public void playMusic(String song)

    pass 2 of 2
    30        call.makeCall("555-5678");31        player.playMusic("Song");32        33        System.out.println("\n=== Duck Typing with Interfaces ===");34        35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String message) {92        System.out.println(model + ": 💬 Sending: " + message);93    }94    95    // From MediaPlayer  //?mediaimpls96    @Override97    public void playMusic(String songSong) {98        System.out.println(modeliPhone 15 + ": 🎵 Playing " + songSong);99    }
    outputiPhone 15: 🎵 Playing Song
    
    === Duck Typing with Interfaces ===
  11. this.model ← Pixel

    pass 2 of 2
    69SmartPhone(String modelPixel) {70    this.model→ Pixel = modelPixel;71}
  12. this.model ← Canon

    35        // Different devices, same interfaces  //?ducktyping36        Camera[] cameras = {37            new SmartPhone("Pixel"),38            new DigitalCamera("Canon"),  //?digitalcam39        };40        41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String message) {92        System.out.println(model + ": 💬 Sending: " + message);93    }94    95    // From MediaPlayer  //?mediaimpls96    @Override97    public void playMusic(String song) {98        System.out.println(model + ": 🎵 Playing " + song);99    }100    101    @Override102    public void playVideo(String video) {103        System.out.println(model + ": ▶️ Playing " + video);104    }105}106107// Another class implementing just Camera  //?partialimpl108class DigitalCamera implements Camera {109    private String model;110    111    DigitalCamera(String modelCanon) {112        this.model→ Canon = modelCanon;113    }
  13. for (Camera c : cameras)

    pass 1 of 2
    41for (Camera c⟨SmartPhone B⟩ : cameras) {42    c.takePhoto();43}
  14. for (Camera c : cameras)

    pass 2 of 2
    41for (Camera c⟨DigitalCamera C⟩ : cameras) {42    c.takePhoto();43}
  15. @Override public void takePhoto()

    41        for (Camera c : cameras) {42            c.takePhoto();43        }44    }45}4647// Interface 1  //?interface148interface Camera {49    void takePhoto();50    void recordVideo();51}5253// Interface 2  //?interface254interface Callable {55    void makeCall(String number);56    void sendText(String message);57}5859// Interface 3  //?interface360interface MediaPlayer {61    void playMusic(String song);62    void playVideo(String video);63}6465// Class implementing MULTIPLE interfaces  //?multipleimpl66class SmartPhone implements Camera, Callable, MediaPlayer {  //?impllist67    private String model;68    69    SmartPhone(String model) {70        this.model = model;71    }72    73    // From Camera  //?cameraimpls74    @Override75    public void takePhoto() {76        System.out.println(model + ": 📷 Taking photo");77    }78    79    @Override80    public void recordVideo() {81        System.out.println(model + ": 🎥 Recording video");82    }83    84    // From Callable  //?callableimpls85    @Override86    public void makeCall(String number) {87        System.out.println(model + ": 📞 Calling " + number);88    }89    90    @Override91    public void sendText(String message) {92        System.out.println(model + ": 💬 Sending: " + message);93    }94    95    // From MediaPlayer  //?mediaimpls96    @Override97    public void playMusic(String song) {98        System.out.println(model + ": 🎵 Playing " + song);99    }100    101    @Override102    public void playVideo(String video) {103        System.out.println(model + ": ▶️ Playing " + video);104    }105}106107// Another class implementing just Camera  //?partialimpl108class DigitalCamera implements Camera {109    private String model;110    111    DigitalCamera(String model) {112        this.model = model;113    }114    115    @Override116    public void takePhoto() {117        System.out.println(modelCanon + " DSLR: 📷 High-quality photo");118    }
    outputCanon DSLR: 📷 High-quality photo

class X implements A, B, C - must implement all methods from all interfaces.

Interface as type

Use interface type for polymorphism.

firstShapeType
InterfaceReference.java
Replay: real traced execution (multi-file project)
// Using Interface as Type

public class InterfaceReference {
    public static void main(String[] args) {
        System.out.println("=== Interface as Method Parameter ===\n");

        Circle circle = new Circle(5);
        Rectangle rect = new Rectangle(4, 6);

        // Pass different types to same method
        printArea(circle);
        printArea(rect);

        System.out.println("\n=== Interface as Return Type ===");

        // Factory method returns interface type
        String firstShapeType = "circle";
        Shape shape1 = createShape(firstShapeType, 3);
        Shape shape2 = createShape("rectangle", 4);

        System.out.println("Created: " + shape1.getName());
        System.out.println("Created: " + shape2.getName());

        System.out.println("\n=== Collection of Interface Type ===");

        Shape[] shapes = {
            createShape("circle", 5),
            createShape("rectangle", 3),
            createShape("circle", 2)
        };

        double totalArea = calculateTotalArea(shapes);
        System.out.println("Total area: " + String.format("%.2f", totalArea));

        System.out.println("\n=== Interface Extends Interface ===");

        // 3DShape extends Shape
        Sphere sphere = new Sphere(4);

        System.out.println("Sphere:");
        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));
        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));

        // Can use as Shape too!
        printArea(sphere);
    }

    // Method with interface parameter
    static void printArea(Shape shape) {
        System.out.println(shape.getName() + " area: " +
                          String.format("%.2f", shape.getArea()));
    }

    // Method with interface return type
    static Shape createShape(String type, double size) {
        return switch(type.toLowerCase()) {
            case "circle" -> new Circle(size);
            case "rectangle" -> new Rectangle(size, size);
            default -> throw new IllegalArgumentException("Unknown shape: " + type);
        };
    }

    // Method processing array of interfaces
    static double calculateTotalArea(Shape[] shapes) {
        double total = 0;
        for (Shape s : shapes) {
            total += s.getArea();
        }
        return total;
    }
}

// Base interface
interface Shape {
    double getArea();
    String getName();
}

// Interface extending interface
interface Shape3D extends Shape {
    double getVolume();
    // Also inherits getArea() and getName()!
}

class Circle implements Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }

    @Override
    public String getName() {
        return "Circle (r=" + radius + ")";
    }
}

class Rectangle implements Shape {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double getArea() {
        return width * height;
    }

    @Override
    public String getName() {
        return "Rectangle (" + width + "x" + height + ")";
    }
}

// Implements extended interface
class Sphere implements Shape3D {
    private double radius;

    Sphere(double radius) {
        this.radius = radius;
    }

    // From Shape (inherited by Shape3D)
    @Override
    public double getArea() {
        return 4 * Math.PI * radius * radius;  // Surface area
    }

    @Override
    public String getName() {
        return "Sphere (r=" + radius + ")";
    }

    // From Shape3D
    @Override
    public double getVolume() {
        return (4.0 / 3.0) * Math.PI * radius * radius * radius;
    }
}

// Using Interface as Type

public class InterfaceReference {
    public static void main(String[] args) {
        System.out.println("=== Interface as Method Parameter ===\n");

        Circle circle = new Circle(5);
        Rectangle rect = new Rectangle(4, 6);

        // Pass different types to same method
        printArea(circle);
        printArea(rect);

        System.out.println("\n=== Interface as Return Type ===");

        // Factory method returns interface type
        String firstShapeType = "rectangle";
        Shape shape1 = createShape(firstShapeType, 3);
        Shape shape2 = createShape("rectangle", 4);

        System.out.println("Created: " + shape1.getName());
        System.out.println("Created: " + shape2.getName());

        System.out.println("\n=== Collection of Interface Type ===");

        Shape[] shapes = {
            createShape("circle", 5),
            createShape("rectangle", 3),
            createShape("circle", 2)
        };

        double totalArea = calculateTotalArea(shapes);
        System.out.println("Total area: " + String.format("%.2f", totalArea));

        System.out.println("\n=== Interface Extends Interface ===");

        // 3DShape extends Shape
        Sphere sphere = new Sphere(4);

        System.out.println("Sphere:");
        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));
        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));

        // Can use as Shape too!
        printArea(sphere);
    }

    // Method with interface parameter
    static void printArea(Shape shape) {
        System.out.println(shape.getName() + " area: " +
                          String.format("%.2f", shape.getArea()));
    }

    // Method with interface return type
    static Shape createShape(String type, double size) {
        return switch(type.toLowerCase()) {
            case "circle" -> new Circle(size);
            case "rectangle" -> new Rectangle(size, size);
            default -> throw new IllegalArgumentException("Unknown shape: " + type);
        };
    }

    // Method processing array of interfaces
    static double calculateTotalArea(Shape[] shapes) {
        double total = 0;
        for (Shape s : shapes) {
            total += s.getArea();
        }
        return total;
    }
}

// Base interface
interface Shape {
    double getArea();
    String getName();
}

// Interface extending interface
interface Shape3D extends Shape {
    double getVolume();
    // Also inherits getArea() and getName()!
}

class Circle implements Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }

    @Override
    public String getName() {
        return "Circle (r=" + radius + ")";
    }
}

class Rectangle implements Shape {
    private double width, height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double getArea() {
        return width * height;
    }

    @Override
    public String getName() {
        return "Rectangle (" + width + "x" + height + ")";
    }
}

// Implements extended interface
class Sphere implements Shape3D {
    private double radius;

    Sphere(double radius) {
        this.radius = radius;
    }

    // From Shape (inherited by Shape3D)
    @Override
    public double getArea() {
        return 4 * Math.PI * radius * radius;  // Surface area
    }

    @Override
    public String getName() {
        return "Sphere (r=" + radius + ")";
    }

    // From Shape3D
    @Override
    public double getVolume() {
        return (4.0 / 3.0) * Math.PI * radius * radius * radius;
    }
}

  1. public static void main(String[] args)

    3public class InterfaceReference {4    public static void main(String[] args) {5        System.out.println("=== Interface as Method Parameter ===\n");6        7        Circle circle = new Circle(5);8        Rectangle rect = new Rectangle(4, 6);
    output=== Interface as Method Parameter ===
  2. this.radius ← 5.0, circle ← ⟨Circle A⟩

    pass 1 of 4
    7        Circle circle→ ⟨Circle A⟩ = new Circle(5);8        Rectangle rect = new Rectangle(4, 6);9        10        // Pass different types to same method  //?samemethod11        printArea(circle);12        printArea(rect);13        14        System.out.println("\n=== Interface as Return Type ===");15        16        // Factory method returns interface type  //?factory17        String firstShapeType = "circle";  //@firstShapeType="circle", "rectangle"18        Shape shape1 = createShape(firstShapeType, 3);19        Shape shape2 = createShape("rectangle", 4);20        21        System.out.println("Created: " + shape1.getName());22        System.out.println("Created: " + shape2.getName());23        24        System.out.println("\n=== Collection of Interface Type ===");25        26        Shape[] shapes = {  //?collection27            createShape("circle", 5),28            createShape("rectangle", 3),29            createShape("circle", 2)30        };31        32        double totalArea = calculateTotalArea(shapes);  //?totalarea33        System.out.println("Total area: " + String.format("%.2f", totalArea));34        35        System.out.println("\n=== Interface Extends Interface ===");36        37        // 3DShape extends Shape  //?extendsinterface38        Sphere sphere = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!  //?shapereference45        printArea(sphere);46    }47    48    // Method with interface parameter  //?interfaceparam49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type  //?interfacereturn55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces  //?processarray64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface  //?shapeinterface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface  //?extendedinterface80interface Shape3D extends Shape {  //?interfaceextends81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius5.0) {89        this.radius→ 5.0 = radius5.0;90    }
    All 4 passes — pass 1 is the card above
    passradiusfirstShapeTypethis.radiuscircleshape1total
    15.05.0⟨Circle A⟩
    23.0circle3.0⟨Circle B⟩
    35.05.0
    42.02.00.0
  3. this.width ← 4.0, this.height ← 6.0, rect ← ⟨Rectangle C⟩

    pass 1 of 3
    7        Circle circle = new Circle(5);8        Rectangle rect→ ⟨Rectangle C⟩ = new Rectangle(4, 6);9        10        // Pass different types to same method  //?samemethod11        printArea(circle⟨Circle A⟩);12        printArea(rect);13        14        System.out.println("\n=== Interface as Return Type ===");15        16        // Factory method returns interface type  //?factory17        String firstShapeType = "circle";  //@firstShapeType="circle", "rectangle"18        Shape shape1 = createShape(firstShapeType, 3);19        Shape shape2 = createShape("rectangle", 4);20        21        System.out.println("Created: " + shape1.getName());22        System.out.println("Created: " + shape2.getName());23        24        System.out.println("\n=== Collection of Interface Type ===");25        26        Shape[] shapes = {  //?collection27            createShape("circle", 5),28            createShape("rectangle", 3),29            createShape("circle", 2)30        };31        32        double totalArea = calculateTotalArea(shapes);  //?totalarea33        System.out.println("Total area: " + String.format("%.2f", totalArea));34        35        System.out.println("\n=== Interface Extends Interface ===");36        37        // 3DShape extends Shape  //?extendsinterface38        Sphere sphere = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!  //?shapereference45        printArea(sphere);46    }47    48    // Method with interface parameter  //?interfaceparam49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type  //?interfacereturn55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces  //?processarray64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface  //?shapeinterface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface  //?extendedinterface80interface Shape3D extends Shape {  //?interfaceextends81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius) {89        this.radius = radius;90    }91    92    @Override93    public double getArea() {94        return Math.PI * radius * radius;95    }96    97    @Override98    public String getName() {99        return "Circle (r=" + radius + ")";100    }101}102103class Rectangle implements Shape {104    private double width, height;105    106    Rectangle(double width4.0, double height6.0) {107        this.width→ 4.0 = width4.0;108        this.height→ 6.0 = height6.0;109    }
    All 3 passes — pass 1 is the card above
    passwidthheightcircleradiusthis.widththis.heightrectshape2total
    14.06.0⟨Circle A⟩5.04.06.0⟨Rectangle C⟩
    24.04.03.04.04.0⟨Rectangle D⟩
    33.03.03.03.00.0
  4. static void printArea(Shape shape)

    pass 1 of 3
    48// Method with interface parameter  //?interfaceparam49static void printArea(Shape shape⟨Circle A⟩) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    All 3 passes — pass 1 is the card above
    passshaperadiuswidthheight
    1⟨Circle A⟩5.0
    2⟨Rectangle C⟩4.06.0
    3⟨Sphere E⟩4.0
  5. @Override public String getName()

    pass 1 of 2
    97@Override98public String getName() {99    return "Circle (r=" + radius5.0 + ")";100}
  6. @Override public double getArea()

    pass 1 of 3
    92@Override93public double getArea() {94    return Math.PI * radius5.0 * radius;95}
    All 3 passes — pass 1 is the card above
    passradius
    15.0
    25.0
    32.0
  7. printArea(circle);

    10    // Pass different types to same method  //?samemethod11    printArea(circle⟨Circle A⟩);12    printArea(rect⟨Rectangle C⟩);13    14    System.out.println("\n=== Interface as Return Type ===");15    16    // Factory method returns interface type  //?factory17    String firstShapeType = "circle";  //@firstShapeType="circle", "rectangle"18    Shape shape1 = createShape(firstShapeType, 3);19    Shape shape2 = createShape("rectangle", 4);20    21    System.out.println("Created: " + shape1.getName());22    System.out.println("Created: " + shape2.getName());23    24    System.out.println("\n=== Collection of Interface Type ===");25    26    Shape[] shapes = {  //?collection27        createShape("circle", 5),28        createShape("rectangle", 3),29        createShape("circle", 2)30    };31    32    double totalArea = calculateTotalArea(shapes);  //?totalarea33    System.out.println("Total area: " + String.format("%.2f", totalArea));34    35    System.out.println("\n=== Interface Extends Interface ===");36    37    // 3DShape extends Shape  //?extendsinterface38    Sphere sphere = new Sphere(4);39    40    System.out.println("Sphere:");41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!  //?shapereference45    printArea(sphere);46}4748// Method with interface parameter  //?interfaceparam49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputCircle (r=5.0) area: 78.54
  8. @Override public String getName()

    pass 1 of 2
    116@Override117public String getName() {118    return "Rectangle (" + width4.0 + "x" + height6.0 + ")";119}
  9. @Override public double getArea()

    pass 1 of 2
    111@Override112public double getArea() {113    return width4.0 * height6.0;114}
  10. firstShapeType ← circle

    11    printArea(circle);12    printArea(rect⟨Rectangle C⟩);13    14    System.out.println("\n=== Interface as Return Type ===");15    16    // Factory method returns interface type  //?factory17    String firstShapeType→ circle = "circle";  //@firstShapeType="circle", "rectangle"18    Shape shape1 = createShape(firstShapeTypecircle, 3);19    Shape shape2 = createShape("rectangle", 4);20    21    System.out.println("Created: " + shape1.getName());22    System.out.println("Created: " + shape2.getName());23    24    System.out.println("\n=== Collection of Interface Type ===");25    26    Shape[] shapes = {  //?collection27        createShape("circle", 5),28        createShape("rectangle", 3),29        createShape("circle", 2)30    };31    32    double totalArea = calculateTotalArea(shapes);  //?totalarea33    System.out.println("Total area: " + String.format("%.2f", totalArea));34    35    System.out.println("\n=== Interface Extends Interface ===");36    37    // 3DShape extends Shape  //?extendsinterface38    Sphere sphere = new Sphere(4);39    40    System.out.println("Sphere:");41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!  //?shapereference45    printArea(sphere);46}4748// Method with interface parameter  //?interfaceparam49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputRectangle (4.0x6.0) area: 24.00
    
    === Interface as Return Type ===
  11. static Shape createShape(String type, double size)

    pass 1 of 5
    54// Method with interface return type  //?interfacereturn55static Shape createShape(String typecircle, double size3.0) {56    return switch(type.toLowerCase()) {57        case "circle" -> new Circle(size);58        case "rectangle" -> new Rectangle(size, size);59        default -> throw new IllegalArgumentException("Unknown shape: " + type);60    };61}
    All 5 passes — pass 1 is the card above
    passtypesizeradiustotal
    1circle3.0
    2rectangle4.03.0
    3circle5.0
    4rectangle3.0
    5circle2.00.0
  12. @Override public String getName()

    pass 2 of 2
    97@Override98public String getName() {99    return "Circle (r=" + radius3.0 + ")";100}
  13. System.out.println("Created: " + shape1.getName());

    21System.out.println("Created: " + shape1.getName());22System.out.println("Created: " + shape2.getName());
    outputCreated: Circle (r=3.0)
  14. @Override public String getName()

    pass 2 of 2
    116@Override117public String getName() {118    return "Rectangle (" + width4.0 + "x" + height4.0 + ")";119}
  15. System.out.println("Created: " + shape2.getName());

    21System.out.println("Created: " + shape1.getName());22System.out.println("Created: " + shape2.getName());2324System.out.println("\n=== Collection of Interface Type ===");2526Shape[] shapes = {  //?collection27    createShape("circle", 5),28    createShape("rectangle", 3),29    createShape("circle", 2)30};
    outputCreated: Rectangle (4.0x4.0)
    
    === Collection of Interface Type ===
  16. total ← 0.0

    63// Method processing array of interfaces  //?processarray64static double calculateTotalArea(Shape[] shapes) {65    double total→ 0.0 = 0;66    for (Shape s : shapes) {
  17. for (Shape s : shapes)

    pass 1 of 3
    65double total = 0;66for (Shape s⟨Circle F⟩ : shapes) {67    total0.0 += s.getArea();68}
    All 3 passes — pass 1 is the card above
    passstotalwidthheight
    1⟨Circle F⟩0.0
    2⟨Rectangle G⟩78.539816339744833.03.0
    3⟨Circle H⟩87.53981633974483
  18. total ← 78.53981633974483

    66for (Shape s : shapes) {67    total→ 78.53981633974483 += s.getArea();68}
  19. @Override public double getArea()

    pass 2 of 2
    111@Override112public double getArea() {113    return width3.0 * height3.0;114}
  20. total ← 87.53981633974483

    66for (Shape s : shapes) {67    total→ 87.53981633974483 += s.getArea();68}
  21. total ← 100.106186954104

    66    for (Shape s : shapes) {67        total→ 100.106186954104 += s.getArea();68    }69    return total100.106186954104;70}
  22. totalArea ← 100.106186954104

    32double totalArea→ 100.106186954104 = calculateTotalArea(shapes);  //?totalarea33System.out.println("Total area: " + String.format("%.2f", totalArea100.106186954104));3435System.out.println("\n=== Interface Extends Interface ===");3637// 3DShape extends Shape  //?extendsinterface38Sphere sphere = new Sphere(4);
    outputTotal area: 100.11
    
    === Interface Extends Interface ===
  23. this.radius ← 4.0, sphere ← ⟨Sphere E⟩

    37        // 3DShape extends Shape  //?extendsinterface38        Sphere sphere→ ⟨Sphere E⟩ = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!  //?shapereference45        printArea(sphere);46    }47    48    // Method with interface parameter  //?interfaceparam49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type  //?interfacereturn55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces  //?processarray64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface  //?shapeinterface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface  //?extendedinterface80interface Shape3D extends Shape {  //?interfaceextends81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius) {89        this.radius = radius;90    }91    92    @Override93    public double getArea() {94        return Math.PI * radius * radius;95    }96    97    @Override98    public String getName() {99        return "Circle (r=" + radius + ")";100    }101}102103class Rectangle implements Shape {104    private double width, height;105    106    Rectangle(double width, double height) {107        this.width = width;108        this.height = height;109    }110    111    @Override112    public double getArea() {113        return width * height;114    }115    116    @Override117    public String getName() {118        return "Rectangle (" + width + "x" + height + ")";119    }120}121122// Implements extended interface  //?impl3d123class Sphere implements Shape3D {124    private double radius;125    126    Sphere(double radius4.0) {127        this.radius→ 4.0 = radius4.0;128    }
    outputSphere:
  24. @Override public double getArea()

    pass 1 of 2
    130// From Shape (inherited by Shape3D)  //?inheritedfrom131@Override132public double getArea() {133    return 4 * Math.PI * radius4.0 * radius;  // Surface area134}
  25. System.out.println(" Area: " + String.format("%.2f", sphere.getArea()…

    40System.out.println("Sphere:");41System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));
    output  Area: 201.06
  26. @Override public double getVolume()

    141// From Shape3D  //?from3d142@Override143public double getVolume() {144    return (4.0 / 3.0) * Math.PI * radius4.0 * radius * radius;145}
  27. printArea(sphere);

    41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!  //?shapereference45    printArea(sphere⟨Sphere E⟩);46}
    output  Volume: 268.08
  28. @Override public String getName()

    136@Override137public String getName() {138    return "Sphere (r=" + radius4.0 + ")";139}
  29. @Override public double getArea()

    pass 2 of 2
    130// From Shape (inherited by Shape3D)  //?inheritedfrom131@Override132public double getArea() {133    return 4 * Math.PI * radius4.0 * radius;  // Surface area134}
  30. printArea(sphere);

    44    // Can use as Shape too!  //?shapereference45    printArea(sphere⟨Sphere E⟩);46}4748// Method with interface parameter  //?interfaceparam49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputSphere (r=4.0) area: 201.06
  1. public static void main(String[] args)

    3public class InterfaceReference {4    public static void main(String[] args) {5        System.out.println("=== Interface as Method Parameter ===\n");6        7        Circle circle = new Circle(5);8        Rectangle rect = new Rectangle(4, 6);
    output=== Interface as Method Parameter ===
  2. this.radius ← 5.0, circle ← ⟨Circle A⟩

    pass 1 of 3
    7        Circle circle→ ⟨Circle A⟩ = new Circle(5);8        Rectangle rect = new Rectangle(4, 6);9        10        // Pass different types to same method11        printArea(circle);12        printArea(rect);13        14        System.out.println("\n=== Interface as Return Type ===");15        16        // Factory method returns interface type17        String firstShapeType = "rectangle";18        Shape shape1 = createShape(firstShapeType, 3);19        Shape shape2 = createShape("rectangle", 4);20        21        System.out.println("Created: " + shape1.getName());22        System.out.println("Created: " + shape2.getName());23        24        System.out.println("\n=== Collection of Interface Type ===");25        26        Shape[] shapes = {27            createShape("circle", 5),28            createShape("rectangle", 3),29            createShape("circle", 2)30        };31        32        double totalArea = calculateTotalArea(shapes);33        System.out.println("Total area: " + String.format("%.2f", totalArea));34        35        System.out.println("\n=== Interface Extends Interface ===");36        37        // 3DShape extends Shape38        Sphere sphere = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!45        printArea(sphere);46    }47    48    // Method with interface parameter49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface80interface Shape3D extends Shape {81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius5.0) {89        this.radius→ 5.0 = radius5.0;90    }
    All 3 passes — pass 1 is the card above
    passradiusthis.radiuscircletotal
    15.05.0⟨Circle A⟩
    25.05.0
    32.02.00.0
  3. this.width ← 4.0, this.height ← 6.0, rect ← ⟨Rectangle B⟩

    pass 1 of 4
    7        Circle circle = new Circle(5);8        Rectangle rect→ ⟨Rectangle B⟩ = new Rectangle(4, 6);9        10        // Pass different types to same method11        printArea(circle⟨Circle A⟩);12        printArea(rect);13        14        System.out.println("\n=== Interface as Return Type ===");15        16        // Factory method returns interface type17        String firstShapeType = "rectangle";18        Shape shape1 = createShape(firstShapeType, 3);19        Shape shape2 = createShape("rectangle", 4);20        21        System.out.println("Created: " + shape1.getName());22        System.out.println("Created: " + shape2.getName());23        24        System.out.println("\n=== Collection of Interface Type ===");25        26        Shape[] shapes = {27            createShape("circle", 5),28            createShape("rectangle", 3),29            createShape("circle", 2)30        };31        32        double totalArea = calculateTotalArea(shapes);33        System.out.println("Total area: " + String.format("%.2f", totalArea));34        35        System.out.println("\n=== Interface Extends Interface ===");36        37        // 3DShape extends Shape38        Sphere sphere = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!45        printArea(sphere);46    }47    48    // Method with interface parameter49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface80interface Shape3D extends Shape {81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius) {89        this.radius = radius;90    }91    92    @Override93    public double getArea() {94        return Math.PI * radius * radius;95    }96    97    @Override98    public String getName() {99        return "Circle (r=" + radius + ")";100    }101}102103class Rectangle implements Shape {104    private double width, height;105    106    Rectangle(double width4.0, double height6.0) {107        this.width→ 4.0 = width4.0;108        this.height→ 6.0 = height6.0;109    }
    All 4 passes — pass 1 is the card above
    passwidthheightcircleradiusfirstShapeTypethis.widththis.heightrectshape1shape2total
    14.06.0⟨Circle A⟩5.04.06.0⟨Rectangle B⟩
    23.03.0rectangle3.03.0⟨Rectangle C⟩
    34.04.04.04.0⟨Rectangle D⟩
    43.03.03.03.00.0
  4. static void printArea(Shape shape)

    pass 1 of 3
    48// Method with interface parameter49static void printArea(Shape shape⟨Circle A⟩) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    All 3 passes — pass 1 is the card above
    passshaperadiuswidthheight
    1⟨Circle A⟩5.0
    2⟨Rectangle B⟩4.06.0
    3⟨Sphere E⟩4.0
  5. @Override public String getName()

    97@Override98public String getName() {99    return "Circle (r=" + radius5.0 + ")";100}
  6. @Override public double getArea()

    pass 1 of 3
    92@Override93public double getArea() {94    return Math.PI * radius5.0 * radius;95}
    All 3 passes — pass 1 is the card above
    passradius
    15.0
    25.0
    32.0
  7. printArea(circle);

    10    // Pass different types to same method11    printArea(circle⟨Circle A⟩);12    printArea(rect⟨Rectangle B⟩);13    14    System.out.println("\n=== Interface as Return Type ===");15    16    // Factory method returns interface type17    String firstShapeType = "rectangle";18    Shape shape1 = createShape(firstShapeType, 3);19    Shape shape2 = createShape("rectangle", 4);20    21    System.out.println("Created: " + shape1.getName());22    System.out.println("Created: " + shape2.getName());23    24    System.out.println("\n=== Collection of Interface Type ===");25    26    Shape[] shapes = {27        createShape("circle", 5),28        createShape("rectangle", 3),29        createShape("circle", 2)30    };31    32    double totalArea = calculateTotalArea(shapes);33    System.out.println("Total area: " + String.format("%.2f", totalArea));34    35    System.out.println("\n=== Interface Extends Interface ===");36    37    // 3DShape extends Shape38    Sphere sphere = new Sphere(4);39    40    System.out.println("Sphere:");41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!45    printArea(sphere);46}4748// Method with interface parameter49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputCircle (r=5.0) area: 78.54
  8. @Override public String getName()

    pass 1 of 3
    116@Override117public String getName() {118    return "Rectangle (" + width4.0 + "x" + height6.0 + ")";119}
    All 3 passes — pass 1 is the card above
    passwidthheight
    14.06.0
    23.03.0
    34.04.0
  9. @Override public double getArea()

    pass 1 of 2
    111@Override112public double getArea() {113    return width4.0 * height6.0;114}
  10. firstShapeType ← rectangle

    11    printArea(circle);12    printArea(rect⟨Rectangle B⟩);13    14    System.out.println("\n=== Interface as Return Type ===");15    16    // Factory method returns interface type17    String firstShapeType→ rectangle = "rectangle";18    Shape shape1 = createShape(firstShapeTyperectangle, 3);19    Shape shape2 = createShape("rectangle", 4);20    21    System.out.println("Created: " + shape1.getName());22    System.out.println("Created: " + shape2.getName());23    24    System.out.println("\n=== Collection of Interface Type ===");25    26    Shape[] shapes = {27        createShape("circle", 5),28        createShape("rectangle", 3),29        createShape("circle", 2)30    };31    32    double totalArea = calculateTotalArea(shapes);33    System.out.println("Total area: " + String.format("%.2f", totalArea));34    35    System.out.println("\n=== Interface Extends Interface ===");36    37    // 3DShape extends Shape38    Sphere sphere = new Sphere(4);39    40    System.out.println("Sphere:");41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!45    printArea(sphere);46}4748// Method with interface parameter49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputRectangle (4.0x6.0) area: 24.00
    
    === Interface as Return Type ===
  11. static Shape createShape(String type, double size)

    pass 1 of 5
    54// Method with interface return type55static Shape createShape(String typerectangle, double size3.0) {56    return switch(type.toLowerCase()) {57        case "circle" -> new Circle(size);58        case "rectangle" -> new Rectangle(size, size);59        default -> throw new IllegalArgumentException("Unknown shape: " + type);60    };61}
    All 5 passes — pass 1 is the card above
    passtypesizetotal
    1rectangle3.0
    2rectangle4.0
    3circle5.0
    4rectangle3.0
    5circle2.00.0
  12. System.out.println("Created: " + shape1.getName());

    21System.out.println("Created: " + shape1.getName());22System.out.println("Created: " + shape2.getName());
    outputCreated: Rectangle (3.0x3.0)
  13. System.out.println("Created: " + shape2.getName());

    21System.out.println("Created: " + shape1.getName());22System.out.println("Created: " + shape2.getName());2324System.out.println("\n=== Collection of Interface Type ===");2526Shape[] shapes = {27    createShape("circle", 5),28    createShape("rectangle", 3),29    createShape("circle", 2)30};
    outputCreated: Rectangle (4.0x4.0)
    
    === Collection of Interface Type ===
  14. total ← 0.0

    63// Method processing array of interfaces64static double calculateTotalArea(Shape[] shapes) {65    double total→ 0.0 = 0;66    for (Shape s : shapes) {
  15. for (Shape s : shapes)

    pass 1 of 3
    65double total = 0;66for (Shape s⟨Circle F⟩ : shapes) {67    total0.0 += s.getArea();68}
    All 3 passes — pass 1 is the card above
    passstotalwidthheight
    1⟨Circle F⟩0.0
    2⟨Rectangle G⟩78.539816339744833.03.0
    3⟨Circle H⟩87.53981633974483
  16. total ← 78.53981633974483

    66for (Shape s : shapes) {67    total→ 78.53981633974483 += s.getArea();68}
  17. @Override public double getArea()

    pass 2 of 2
    111@Override112public double getArea() {113    return width3.0 * height3.0;114}
  18. total ← 87.53981633974483

    66for (Shape s : shapes) {67    total→ 87.53981633974483 += s.getArea();68}
  19. total ← 100.106186954104

    66    for (Shape s : shapes) {67        total→ 100.106186954104 += s.getArea();68    }69    return total100.106186954104;70}
  20. totalArea ← 100.106186954104

    32double totalArea→ 100.106186954104 = calculateTotalArea(shapes);33System.out.println("Total area: " + String.format("%.2f", totalArea100.106186954104));3435System.out.println("\n=== Interface Extends Interface ===");3637// 3DShape extends Shape38Sphere sphere = new Sphere(4);
    outputTotal area: 100.11
    
    === Interface Extends Interface ===
  21. this.radius ← 4.0, sphere ← ⟨Sphere E⟩

    37        // 3DShape extends Shape38        Sphere sphere→ ⟨Sphere E⟩ = new Sphere(4);39        40        System.out.println("Sphere:");41        System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42        System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43        44        // Can use as Shape too!45        printArea(sphere);46    }47    48    // Method with interface parameter49    static void printArea(Shape shape) {50        System.out.println(shape.getName() + " area: " + 51                          String.format("%.2f", shape.getArea()));52    }53    54    // Method with interface return type55    static Shape createShape(String type, double size) {56        return switch(type.toLowerCase()) {57            case "circle" -> new Circle(size);58            case "rectangle" -> new Rectangle(size, size);59            default -> throw new IllegalArgumentException("Unknown shape: " + type);60        };61    }62    63    // Method processing array of interfaces64    static double calculateTotalArea(Shape[] shapes) {65        double total = 0;66        for (Shape s : shapes) {67            total += s.getArea();68        }69        return total;70    }71}7273// Base interface74interface Shape {75    double getArea();76    String getName();77}7879// Interface extending interface80interface Shape3D extends Shape {81    double getVolume();82    // Also inherits getArea() and getName()!83}8485class Circle implements Shape {86    private double radius;87    88    Circle(double radius) {89        this.radius = radius;90    }91    92    @Override93    public double getArea() {94        return Math.PI * radius * radius;95    }96    97    @Override98    public String getName() {99        return "Circle (r=" + radius + ")";100    }101}102103class Rectangle implements Shape {104    private double width, height;105    106    Rectangle(double width, double height) {107        this.width = width;108        this.height = height;109    }110    111    @Override112    public double getArea() {113        return width * height;114    }115    116    @Override117    public String getName() {118        return "Rectangle (" + width + "x" + height + ")";119    }120}121122// Implements extended interface123class Sphere implements Shape3D {124    private double radius;125    126    Sphere(double radius4.0) {127        this.radius→ 4.0 = radius4.0;128    }
    outputSphere:
  22. @Override public double getArea()

    pass 1 of 2
    130// From Shape (inherited by Shape3D)131@Override132public double getArea() {133    return 4 * Math.PI * radius4.0 * radius;  // Surface area134}
  23. System.out.println(" Area: " + String.format("%.2f", sphere.getArea()…

    40System.out.println("Sphere:");41System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));
    output  Area: 201.06
  24. @Override public double getVolume()

    141// From Shape3D142@Override143public double getVolume() {144    return (4.0 / 3.0) * Math.PI * radius4.0 * radius * radius;145}
  25. printArea(sphere);

    41    System.out.println("  Area: " + String.format("%.2f", sphere.getArea()));42    System.out.println("  Volume: " + String.format("%.2f", sphere.getVolume()));43    44    // Can use as Shape too!45    printArea(sphere⟨Sphere E⟩);46}
    output  Volume: 268.08
  26. @Override public String getName()

    136@Override137public String getName() {138    return "Sphere (r=" + radius4.0 + ")";139}
  27. @Override public double getArea()

    pass 2 of 2
    130// From Shape (inherited by Shape3D)131@Override132public double getArea() {133    return 4 * Math.PI * radius4.0 * radius;  // Surface area134}
  28. printArea(sphere);

    44    // Can use as Shape too!45    printArea(sphere⟨Sphere E⟩);46}4748// Method with interface parameter49static void printArea(Shape shape) {50    System.out.println(shape.getName() + " area: " + 51                      String.format("%.2f", shape.getArea()));52}
    outputSphere (r=4.0) area: 201.06

Drawable d = new Circle() - variable type is interface, object is implementing class.

Default methods

Interfaces can provide default implementations (Java 8+).

DefaultMethods.java
Replay: real traced execution (multi-file project)
// Default Methods (Java 8+)

public class DefaultMethods {
    public static void main(String[] args) {
        System.out.println("=== Default Methods in Interfaces ===\n");

        // BasicPrinter uses default log()
        BasicPrinter basic = new BasicPrinter();
        basic.print("Hello");
        basic.log("Starting print job");

        System.out.println("\n=== Overriding Default Method ===");

        // AdvancedPrinter overrides log()
        AdvancedPrinter advanced = new AdvancedPrinter();
        advanced.print("Document");
        advanced.log("Print initiated");

        System.out.println("\n=== Static Methods in Interface ===");

        // Call static method on interface
        String version = Printable.getVersion();
        System.out.println("Printable version: " + version);

        System.out.println("\n=== Multiple Interfaces with Same Default ===");

        MultiDevice device = new MultiDevice();
        device.connect();

        System.out.println("\n=== Why Default Methods? ===");
        System.out.println("""
        Before Java 8:
        - Adding method to interface broke all implementations
        - Every class needed updating

        With default methods:
        - Add new methods with default implementation
        - Existing classes still work
        - Optional override for custom behavior

        Real examples:
        - List.sort() - added in Java 8
        - Collection.stream() - added in Java 8
        """);
    }
}

// Interface with default method
interface Printable {
    // Abstract method - must implement
    void print(String content);

    // Default method - optional to override
    default void log(String message) {
        System.out.println("[LOG] " + message);
    }

    // Another default method
    default void preview() {
        System.out.println("Showing preview...");
    }

    // Static method in interface
    static String getVersion() {
        return "1.0";
    }
}

// Uses default implementation
class BasicPrinter implements Printable {

    @Override
    public void print(String content) {
        System.out.println("Printing: " + content);
    }

    // Does NOT override log() - uses default
    // Does NOT override preview() - uses default
}

// Overrides default method
class AdvancedPrinter implements Printable {

    @Override
    public void print(String content) {
        System.out.println("Advanced printing: " + content);
    }

    @Override
    public void log(String message) {
        System.out.println("[ADVANCED LOG] " +
                          java.time.LocalTime.now() + " - " + message);
    }
}

// Two interfaces with same default method
interface USB {
    default void connect() {
        System.out.println("USB connecting...");
    }
}

interface Bluetooth {
    default void connect() {
        System.out.println("Bluetooth connecting...");
    }
}

// Must resolve conflict
class MultiDevice implements USB, Bluetooth {

    @Override
    public void connect() {
        System.out.println("Multi-device connecting:");
        USB.super.connect();
        Bluetooth.super.connect();
    }
}

  1. basic ← ⟨BasicPrinter A⟩

    3public class DefaultMethods {4    public static void main(String[] args) {5        System.out.println("=== Default Methods in Interfaces ===\n");6        7        // BasicPrinter uses default log()  //?usedefault8        BasicPrinter basic→ ⟨BasicPrinter A⟩ = new BasicPrinter();9        basic.print("Hello");10        basic.log("Starting print job");  //?defaultcall
    output=== Default Methods in Interfaces ===
  2. @Override public void print(String content)

    8        BasicPrinter basic = new BasicPrinter();9        basic.print("Hello");10        basic.log("Starting print job");  //?defaultcall11        12        System.out.println("\n=== Overriding Default Method ===");13        14        // AdvancedPrinter overrides log()  //?overridedefault15        AdvancedPrinter advanced = new AdvancedPrinter();16        advanced.print("Document");17        advanced.log("Print initiated");  //?overriddencall18        19        System.out.println("\n=== Static Methods in Interface ===");20        21        // Call static method on interface  //?staticmethod22        String version = Printable.getVersion();  //?staticcall23        System.out.println("Printable version: " + version);24        25        System.out.println("\n=== Multiple Interfaces with Same Default ===");26        27        MultiDevice device = new MultiDevice();28        device.connect();  //?conflictresolved29        30        System.out.println("\n=== Why Default Methods? ===");31        System.out.println("""32        Before Java 8:33        - Adding method to interface broke all implementations34        - Every class needed updating35        36        With default methods:37        - Add new methods with default implementation38        - Existing classes still work39        - Optional override for custom behavior40        41        Real examples:42        - List.sort() - added in Java 843        - Collection.stream() - added in Java 844        """);45    }46}4748// Interface with default method  //?interfacedefault49interface Printable {50    // Abstract method - must implement  //?abstract51    void print(String content);52    53    // Default method - optional to override  //?defaultmethod54    default void log(String message) {  //?defaultkeyword55        System.out.println("[LOG] " + message);56    }57    58    // Another default method59    default void preview() {60        System.out.println("Showing preview...");61    }62    63    // Static method in interface  //?staticinterface64    static String getVersion() {65        return "1.0";66    }67}6869// Uses default implementation  //?usesdefault70class BasicPrinter implements Printable {71    72    @Override73    public void print(String contentHello) {74        System.out.println("Printing: " + contentHello);75    }
    outputPrinting: Hello
  3. advanced ← ⟨AdvancedPrinter B⟩

    9        basic.print("Hello");10        basic.log("Starting print job");  //?defaultcall11        12        System.out.println("\n=== Overriding Default Method ===");13        14        // AdvancedPrinter overrides log()  //?overridedefault15        AdvancedPrinter advanced→ ⟨AdvancedPrinter B⟩ = new AdvancedPrinter();16        advanced.print("Document");17        advanced.log("Print initiated");  //?overriddencall18        19        System.out.println("\n=== Static Methods in Interface ===");20        21        // Call static method on interface  //?staticmethod22        String version = Printable.getVersion();  //?staticcall23        System.out.println("Printable version: " + version);24        25        System.out.println("\n=== Multiple Interfaces with Same Default ===");26        27        MultiDevice device = new MultiDevice();28        device.connect();  //?conflictresolved29        30        System.out.println("\n=== Why Default Methods? ===");31        System.out.println("""32        Before Java 8:33        - Adding method to interface broke all implementations34        - Every class needed updating35        36        With default methods:37        - Add new methods with default implementation38        - Existing classes still work39        - Optional override for custom behavior40        41        Real examples:42        - List.sort() - added in Java 843        - Collection.stream() - added in Java 844        """);45    }46}4748// Interface with default method  //?interfacedefault49interface Printable {50    // Abstract method - must implement  //?abstract51    void print(String content);52    53    // Default method - optional to override  //?defaultmethod54    default void log(String messageStarting print job) {  //?defaultkeyword55        System.out.println("[LOG] " + messageStarting print job);56    }
    output[LOG] Starting print job
    
    === Overriding Default Method ===
  4. @Override public void print(String content)

    15        AdvancedPrinter advanced = new AdvancedPrinter();16        advanced.print("Document");17        advanced.log("Print initiated");  //?overriddencall18        19        System.out.println("\n=== Static Methods in Interface ===");20        21        // Call static method on interface  //?staticmethod22        String version = Printable.getVersion();  //?staticcall23        System.out.println("Printable version: " + version);24        25        System.out.println("\n=== Multiple Interfaces with Same Default ===");26        27        MultiDevice device = new MultiDevice();28        device.connect();  //?conflictresolved29        30        System.out.println("\n=== Why Default Methods? ===");31        System.out.println("""32        Before Java 8:33        - Adding method to interface broke all implementations34        - Every class needed updating35        36        With default methods:37        - Add new methods with default implementation38        - Existing classes still work39        - Optional override for custom behavior40        41        Real examples:42        - List.sort() - added in Java 843        - Collection.stream() - added in Java 844        """);45    }46}4748// Interface with default method  //?interfacedefault49interface Printable {50    // Abstract method - must implement  //?abstract51    void print(String content);52    53    // Default method - optional to override  //?defaultmethod54    default void log(String message) {  //?defaultkeyword55        System.out.println("[LOG] " + message);56    }57    58    // Another default method59    default void preview() {60        System.out.println("Showing preview...");61    }62    63    // Static method in interface  //?staticinterface64    static String getVersion() {65        return "1.0";66    }67}6869// Uses default implementation  //?usesdefault70class BasicPrinter implements Printable {71    72    @Override73    public void print(String content) {74        System.out.println("Printing: " + content);75    }76    77    // Does NOT override log() - uses default78    // Does NOT override preview() - uses default79}8081// Overrides default method  //?overridesdefault82class AdvancedPrinter implements Printable {83    84    @Override85    public void print(String contentDocument) {86        System.out.println("Advanced printing: " + contentDocument);87    }
    outputAdvanced printing: Document
  5. @Override public void log(String message)

    16        advanced.print("Document");17        advanced.log("Print initiated");  //?overriddencall18        19        System.out.println("\n=== Static Methods in Interface ===");20        21        // Call static method on interface  //?staticmethod22        String version = Printable.getVersion();  //?staticcall23        System.out.println("Printable version: " + version);24        25        System.out.println("\n=== Multiple Interfaces with Same Default ===");26        27        MultiDevice device = new MultiDevice();28        device.connect();  //?conflictresolved29        30        System.out.println("\n=== Why Default Methods? ===");31        System.out.println("""32        Before Java 8:33        - Adding method to interface broke all implementations34        - Every class needed updating35        36        With default methods:37        - Add new methods with default implementation38        - Existing classes still work39        - Optional override for custom behavior40        41        Real examples:42        - List.sort() - added in Java 843        - Collection.stream() - added in Java 844        """);45    }46}4748// Interface with default method  //?interfacedefault49interface Printable {50    // Abstract method - must implement  //?abstract51    void print(String content);52    53    // Default method - optional to override  //?defaultmethod54    default void log(String message) {  //?defaultkeyword55        System.out.println("[LOG] " + message);56    }57    58    // Another default method59    default void preview() {60        System.out.println("Showing preview...");61    }62    63    // Static method in interface  //?staticinterface64    static String getVersion() {65        return "1.0";66    }67}6869// Uses default implementation  //?usesdefault70class BasicPrinter implements Printable {71    72    @Override73    public void print(String content) {74        System.out.println("Printing: " + content);75    }76    77    // Does NOT override log() - uses default78    // Does NOT override preview() - uses default79}8081// Overrides default method  //?overridesdefault82class AdvancedPrinter implements Printable {83    84    @Override85    public void print(String content) {86        System.out.println("Advanced printing: " + content);87    }88    89    @Override90    public void log(String messagePrint initiated) {  //?overridelog91        System.out.println("[ADVANCED LOG] " + 92                          java.time.LocalTime.now() + " - " + messagePrint initiated);93    }
    output[ADVANCED LOG] 23:01:20.249419147 - Print initiated
    
    === Static Methods in Interface ===
  6. version ← 1.0, device ← ⟨MultiDevice C⟩

    21// Call static method on interface  //?staticmethod22String version→ 1.0 = Printable.getVersion();  //?staticcall23System.out.println("Printable version: " + version1.0);2425System.out.println("\n=== Multiple Interfaces with Same Default ===");2627MultiDevice device→ ⟨MultiDevice C⟩ = new MultiDevice();28device.connect();  //?conflictresolved
    outputPrintable version: 1.0
    
    === Multiple Interfaces with Same Default ===
  7. @Override public void connect()

    112@Override113public void connect() {  //?mustoverride114    System.out.println("Multi-device connecting:");115    USB.super.connect();        //?superusb116    Bluetooth.super.connect();  //?superbluetooth
    outputMulti-device connecting:
  8. default void connect()

    97interface USB {98    default void connect() {99        System.out.println("USB connecting...");100    }
    outputUSB connecting...
  9. USB.super.connect(); //?superusb

    114    System.out.println("Multi-device connecting:");115    USB.super.connect();        //?superusb116    Bluetooth.super.connect();  //?superbluetooth117}
  10. default void connect()

    103interface Bluetooth {104    default void connect() {105        System.out.println("Bluetooth connecting...");106    }
    outputBluetooth connecting...
  11. Bluetooth.super.connect(); //?superbluetooth

    27        MultiDevice device = new MultiDevice();28        device.connect();  //?conflictresolved29        30        System.out.println("\n=== Why Default Methods? ===");31        System.out.println("""32        Before Java 8:33        - Adding method to interface broke all implementations34        - Every class needed updating35        36        With default methods:37        - Add new methods with default implementation38        - Existing classes still work39        - Optional override for custom behavior40        41        Real examples:42        - List.sort() - added in Java 843        - Collection.stream() - added in Java 844        """);45    }46}4748// Interface with default method  //?interfacedefault49interface Printable {50    // Abstract method - must implement  //?abstract51    void print(String content);52    53    // Default method - optional to override  //?defaultmethod54    default void log(String message) {  //?defaultkeyword55        System.out.println("[LOG] " + message);56    }57    58    // Another default method59    default void preview() {60        System.out.println("Showing preview...");61    }62    63    // Static method in interface  //?staticinterface64    static String getVersion() {65        return "1.0";66    }67}6869// Uses default implementation  //?usesdefault70class BasicPrinter implements Printable {71    72    @Override73    public void print(String content) {74        System.out.println("Printing: " + content);75    }76    77    // Does NOT override log() - uses default78    // Does NOT override preview() - uses default79}8081// Overrides default method  //?overridesdefault82class AdvancedPrinter implements Printable {83    84    @Override85    public void print(String content) {86        System.out.println("Advanced printing: " + content);87    }88    89    @Override90    public void log(String message) {  //?overridelog91        System.out.println("[ADVANCED LOG] " + 92                          java.time.LocalTime.now() + " - " + message);93    }94}9596// Two interfaces with same default method  //?conflict97interface USB {98    default void connect() {99        System.out.println("USB connecting...");100    }101}102103interface Bluetooth {104    default void connect() {105        System.out.println("Bluetooth connecting...");106    }107}108109// Must resolve conflict  //?resolveconflict110class MultiDevice implements USB, Bluetooth {111    112    @Override113    public void connect() {  //?mustoverride114        System.out.println("Multi-device connecting:");115        USB.super.connect();        //?superusb116        Bluetooth.super.connect();  //?superbluetooth117    }
    output
    === Why Default Methods? ===
    Before Java 8:
    - Adding method to interface broke all implementations
    - Every class needed updating
    
    With default methods:
    - Add new methods with default implementation
    - Existing classes still work
    - Optional override for custom behavior
    
    Real examples:
    - List.sort() - added in Java 8
    - Collection.stream() - added in Java 8

default void method() { } - provides implementation that classes can inherit or override.

default method Interface method with implementation. Classes inherit it unless they override.

Functional interfaces

Interfaces with exactly one abstract method work with lambdas.

example
FunctionalInterfaceDemo.java
Replay: real traced execution (multi-file project)
// Functional Interfaces and Lambdas

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        System.out.println("=== Functional Interface ===\n");

        // Traditional: Anonymous inner class
        Calculator add1 = new Calculator() {
            @Override
            public int calculate(int a, int b) {
                return a + b;
            }
        };

        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));

        // Modern: Lambda expression
        Calculator add2 = (a, b) -> a + b;

        System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));

        System.out.println("\n=== Multiple Operations ===");

        // Different operations, same interface
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        Calculator divide = (a, b) -> a / b;
        Calculator max = (a, b) -> a > b ? a : b;

        int x = 10;
        int y = 4;
        System.out.println(x + " + " + y + " = " + add2.calculate(x, y));
        System.out.println(x + " - " + y + " = " + subtract.calculate(x, y));
        System.out.println(x + " * " + y + " = " + multiply.calculate(x, y));
        System.out.println(x + " / " + y + " = " + divide.calculate(x, y));
        System.out.println("max(" + x + ", " + y + ") = " + max.calculate(x, y));

        System.out.println("\n=== Passing Lambda to Method ===");

        // Pass behavior as parameter
        applyOperation("Addition", 7, 3, (a, b) -> a + b);
        applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));

        System.out.println("\n=== Lambda Variations ===");

        // Single parameter
        Greeter hello = name -> "Hello, " + name + "!";
        System.out.println(hello.greet("World"));

        // Multi-line body
        Greeter formal = name -> {
            String title = "Dear " + name;
            return title + ", welcome!";
        };
        System.out.println(formal.greet("Guest"));

        // No parameters
        MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;
        System.out.println(supplier.get());

        System.out.println("\n=== @FunctionalInterface ===");
        System.out.println("""
        @FunctionalInterface annotation:
        - Documents intent
        - Compiler enforces single abstract method
        - Enables lambda usage

        Common built-in functional interfaces:
        - Runnable: () -> void
        - Comparator<T>: (T, T) -> int
        - Consumer<T>: (T) -> void
        - Supplier<T>: () -> T
        - Function<T, R>: (T) -> R
        - Predicate<T>: (T) -> boolean
        """);
    }

    // Method accepting functional interface
    static void applyOperation(String name, int a, int b, Calculator calc) {
        int result = calc.calculate(a, b);
        System.out.println(name + ": " + a + " op " + b + " = " + result);
    }
}

// Functional interface - exactly ONE abstract method
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);

    // Default methods allowed!
    default void printResult(int a, int b) {
        System.out.println("Result: " + calculate(a, b));
    }
}

// Another functional interface
@FunctionalInterface
interface Greeter {
    String greet(String name);
}

@FunctionalInterface
interface MessageSupplier {
    String get();
}

// Functional Interfaces and Lambdas

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        System.out.println("=== Functional Interface ===\n");

        // Traditional: Anonymous inner class
        Calculator add1 = new Calculator() {
            @Override
            public int calculate(int a, int b) {
                return a + b;
            }
        };

        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));

        // Modern: Lambda expression
        Calculator add2 = (a, b) -> a + b;

        System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));

        System.out.println("\n=== Multiple Operations ===");

        // Different operations, same interface
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        Calculator divide = (a, b) -> a / b;
        Calculator max = (a, b) -> a > b ? a : b;

        int x = 6;
        int y = 4;
        System.out.println(x + " + " + y + " = " + add2.calculate(x, y));
        System.out.println(x + " - " + y + " = " + subtract.calculate(x, y));
        System.out.println(x + " * " + y + " = " + multiply.calculate(x, y));
        System.out.println(x + " / " + y + " = " + divide.calculate(x, y));
        System.out.println("max(" + x + ", " + y + ") = " + max.calculate(x, y));

        System.out.println("\n=== Passing Lambda to Method ===");

        // Pass behavior as parameter
        applyOperation("Addition", 7, 3, (a, b) -> a + b);
        applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));

        System.out.println("\n=== Lambda Variations ===");

        // Single parameter
        Greeter hello = name -> "Hello, " + name + "!";
        System.out.println(hello.greet("World"));

        // Multi-line body
        Greeter formal = name -> {
            String title = "Dear " + name;
            return title + ", welcome!";
        };
        System.out.println(formal.greet("Guest"));

        // No parameters
        MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;
        System.out.println(supplier.get());

        System.out.println("\n=== @FunctionalInterface ===");
        System.out.println("""
        @FunctionalInterface annotation:
        - Documents intent
        - Compiler enforces single abstract method
        - Enables lambda usage

        Common built-in functional interfaces:
        - Runnable: () -> void
        - Comparator<T>: (T, T) -> int
        - Consumer<T>: (T) -> void
        - Supplier<T>: () -> T
        - Function<T, R>: (T) -> R
        - Predicate<T>: (T) -> boolean
        """);
    }

    // Method accepting functional interface
    static void applyOperation(String name, int a, int b, Calculator calc) {
        int result = calc.calculate(a, b);
        System.out.println(name + ": " + a + " op " + b + " = " + result);
    }
}

// Functional interface - exactly ONE abstract method
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);

    // Default methods allowed!
    default void printResult(int a, int b) {
        System.out.println("Result: " + calculate(a, b));
    }
}

// Another functional interface
@FunctionalInterface
interface Greeter {
    String greet(String name);
}

@FunctionalInterface
interface MessageSupplier {
    String get();
}

// Functional Interfaces and Lambdas

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        System.out.println("=== Functional Interface ===\n");

        // Traditional: Anonymous inner class
        Calculator add1 = new Calculator() {
            @Override
            public int calculate(int a, int b) {
                return a + b;
            }
        };

        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));

        // Modern: Lambda expression
        Calculator add2 = (a, b) -> a + b;

        System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));

        System.out.println("\n=== Multiple Operations ===");

        // Different operations, same interface
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        Calculator divide = (a, b) -> a / b;
        Calculator max = (a, b) -> a > b ? a : b;

        int x = 10;
        int y = 2;
        System.out.println(x + " + " + y + " = " + add2.calculate(x, y));
        System.out.println(x + " - " + y + " = " + subtract.calculate(x, y));
        System.out.println(x + " * " + y + " = " + multiply.calculate(x, y));
        System.out.println(x + " / " + y + " = " + divide.calculate(x, y));
        System.out.println("max(" + x + ", " + y + ") = " + max.calculate(x, y));

        System.out.println("\n=== Passing Lambda to Method ===");

        // Pass behavior as parameter
        applyOperation("Addition", 7, 3, (a, b) -> a + b);
        applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));

        System.out.println("\n=== Lambda Variations ===");

        // Single parameter
        Greeter hello = name -> "Hello, " + name + "!";
        System.out.println(hello.greet("World"));

        // Multi-line body
        Greeter formal = name -> {
            String title = "Dear " + name;
            return title + ", welcome!";
        };
        System.out.println(formal.greet("Guest"));

        // No parameters
        MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;
        System.out.println(supplier.get());

        System.out.println("\n=== @FunctionalInterface ===");
        System.out.println("""
        @FunctionalInterface annotation:
        - Documents intent
        - Compiler enforces single abstract method
        - Enables lambda usage

        Common built-in functional interfaces:
        - Runnable: () -> void
        - Comparator<T>: (T, T) -> int
        - Consumer<T>: (T) -> void
        - Supplier<T>: () -> T
        - Function<T, R>: (T) -> R
        - Predicate<T>: (T) -> boolean
        """);
    }

    // Method accepting functional interface
    static void applyOperation(String name, int a, int b, Calculator calc) {
        int result = calc.calculate(a, b);
        System.out.println(name + ": " + a + " op " + b + " = " + result);
    }
}

// Functional interface - exactly ONE abstract method
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);

    // Default methods allowed!
    default void printResult(int a, int b) {
        System.out.println("Result: " + calculate(a, b));
    }
}

// Another functional interface
@FunctionalInterface
interface Greeter {
    String greet(String name);
}

@FunctionalInterface
interface MessageSupplier {
    String get();
}

  1. add1 ← ⟨FunctionalInterfaceDemo$1 A⟩

    3public class FunctionalInterfaceDemo {4    public static void main(String[] args) {5        System.out.println("=== Functional Interface ===\n");6        7        // Traditional: Anonymous inner class  //?anonymous8        Calculator add1→ ⟨FunctionalInterfaceDemo$1 A⟩ = new Calculator() {9            @Override10            public int calculate(int a, int b) {11                return a + b;12            }13        };14        15        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));
    output=== Functional Interface ===
  2. @Override public int calculate(int a, int b)

    8Calculator add1 = new Calculator() {9    @Override10    public int calculate(int a5, int b3) {11        return a5 + b3;12    }
  3. add2 ← ⟨FunctionalInterfaceDemo lambda B⟩, subtract ← ⟨FunctionalInterfaceDemo lambda C⟩

    15System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));1617// Modern: Lambda expression  //?lambda18Calculator add2→ ⟨FunctionalInterfaceDemo lambda B⟩ = (a, b) -> a + b;  //?lambdasyntax1920System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));2122System.out.println("\n=== Multiple Operations ===");2324// Different operations, same interface  //?operations25Calculator subtract→ ⟨FunctionalInterfaceDemo lambda C⟩ = (a, b) -> a - b;26Calculator multiply→ ⟨FunctionalInterfaceDemo lambda D⟩ = (a, b) -> a * b;27Calculator divide→ ⟨FunctionalInterfaceDemo lambda E⟩ = (a, b) -> a / b;28Calculator max→ ⟨FunctionalInterfaceDemo lambda F⟩ = (a, b) -> a > b ? a : b;  //?ternary2930int x→ 10 = 10;  //@x=631int y→ 4 = 4;  //@y=232System.out.println(x10 + " + " + y4 + " = " + add2.calculate(x, y));33System.out.println(x10 + " - " + y4 + " = " + subtract.calculate(x, y));34System.out.println(x10 + " * " + y4 + " = " + multiply.calculate(x, y));35System.out.println(x10 + " / " + y4 + " = " + divide.calculate(x, y));36System.out.println("max(" + x10 + ", " + y4 + ") = " + max.calculate(x, y));3738System.out.println("\n=== Passing Lambda to Method ===");3940// Pass behavior as parameter  //?passlambda41applyOperation("Addition", 7, 3, (a, b) -> a + b);42applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));
    outputAnonymous class: 5 + 3 = 8
    Lambda: 5 + 3 = 8
    
    === Multiple Operations ===
    10 + 4 = 14
    10 - 4 = 6
    10 * 4 = 40
    10 / 4 = 2
    max(10, 4) = 10
    
    === Passing Lambda to Method ===
  4. result ← 10

    pass 1 of 2
    40    // Pass behavior as parameter  //?passlambda41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter  //?singleparam47    Greeter hello = name -> "Hello, " + name + "!";  //?noparens48    System.out.println(hello.greet("World"));49    50    // Multi-line body  //?multiline51    Greeter formal = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters  //?noparam58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface  //?methodaccept79static void applyOperation(String nameAddition, int a7, int b3, Calculator calc⟨FunctionalInterfaceDemo lambda G⟩) {80    int result→ 10 = calc.calculate(a7, b3);81    System.out.println(nameAddition + ": " + a7 + " op " + b3 + " = " + result10);82}
    outputAddition: 7 op 3 = 10
  5. result ← 256, hello ← ⟨FunctionalInterfaceDemo lambda H⟩, formal ← ⟨FunctionalInterfaceDemo lambda I⟩

    pass 2 of 2
    41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter  //?singleparam47    Greeter hello→ ⟨FunctionalInterfaceDemo lambda H⟩ = name -> "Hello, " + name + "!";  //?noparens48    System.out.println(hello.greet("World"));49    50    // Multi-line body  //?multiline51    Greeter formal→ ⟨FunctionalInterfaceDemo lambda I⟩ = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters  //?noparam58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface  //?methodaccept79static void applyOperation(String namePower, int a2, int b8, Calculator calc⟨FunctionalInterfaceDemo lambda J⟩) {80    int result→ 256 = calc.calculate(a2, b8);81    System.out.println(namePower + ": " + a2 + " op " + b8 + " = " + result256);82}
    outputPower: 2 op 8 = 256
    
    === Lambda Variations ===
    Hello, World!
  6. supplier ← ⟨FunctionalInterfaceDemo lambda K⟩

    54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters  //?noparam58    MessageSupplier supplier→ ⟨FunctionalInterfaceDemo lambda K⟩ = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}
    outputDear Guest, welcome!
    Sample message at 1736937000000
    
    === @FunctionalInterface ===
    @FunctionalInterface annotation:
    - Documents intent
    - Compiler enforces single abstract method
    - Enables lambda usage
    
    Common built-in functional interfaces:
    - Runnable: () -> void
    - Comparator<T>: (T, T) -> int
    - Consumer<T>: (T) -> void
    - Supplier<T>: () -> T
    - Function<T, R>: (T) -> R
    - Predicate<T>: (T) -> boolean
  1. add1 ← ⟨FunctionalInterfaceDemo$1 A⟩

    3public class FunctionalInterfaceDemo {4    public static void main(String[] args) {5        System.out.println("=== Functional Interface ===\n");6        7        // Traditional: Anonymous inner class8        Calculator add1→ ⟨FunctionalInterfaceDemo$1 A⟩ = new Calculator() {9            @Override10            public int calculate(int a, int b) {11                return a + b;12            }13        };14        15        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));
    output=== Functional Interface ===
  2. @Override public int calculate(int a, int b)

    8Calculator add1 = new Calculator() {9    @Override10    public int calculate(int a5, int b3) {11        return a5 + b3;12    }
  3. add2 ← ⟨FunctionalInterfaceDemo lambda B⟩, subtract ← ⟨FunctionalInterfaceDemo lambda C⟩

    15System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));1617// Modern: Lambda expression18Calculator add2→ ⟨FunctionalInterfaceDemo lambda B⟩ = (a, b) -> a + b;1920System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));2122System.out.println("\n=== Multiple Operations ===");2324// Different operations, same interface25Calculator subtract→ ⟨FunctionalInterfaceDemo lambda C⟩ = (a, b) -> a - b;26Calculator multiply→ ⟨FunctionalInterfaceDemo lambda D⟩ = (a, b) -> a * b;27Calculator divide→ ⟨FunctionalInterfaceDemo lambda E⟩ = (a, b) -> a / b;28Calculator max→ ⟨FunctionalInterfaceDemo lambda F⟩ = (a, b) -> a > b ? a : b;2930int x→ 6 = 6;31int y→ 4 = 4;32System.out.println(x6 + " + " + y4 + " = " + add2.calculate(x, y));33System.out.println(x6 + " - " + y4 + " = " + subtract.calculate(x, y));34System.out.println(x6 + " * " + y4 + " = " + multiply.calculate(x, y));35System.out.println(x6 + " / " + y4 + " = " + divide.calculate(x, y));36System.out.println("max(" + x6 + ", " + y4 + ") = " + max.calculate(x, y));3738System.out.println("\n=== Passing Lambda to Method ===");3940// Pass behavior as parameter41applyOperation("Addition", 7, 3, (a, b) -> a + b);42applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));
    outputAnonymous class: 5 + 3 = 8
    Lambda: 5 + 3 = 8
    
    === Multiple Operations ===
    6 + 4 = 10
    6 - 4 = 2
    6 * 4 = 24
    6 / 4 = 1
    max(6, 4) = 6
    
    === Passing Lambda to Method ===
  4. result ← 10

    pass 1 of 2
    40    // Pass behavior as parameter41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter47    Greeter hello = name -> "Hello, " + name + "!";48    System.out.println(hello.greet("World"));49    50    // Multi-line body51    Greeter formal = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface79static void applyOperation(String nameAddition, int a7, int b3, Calculator calc⟨FunctionalInterfaceDemo lambda G⟩) {80    int result→ 10 = calc.calculate(a7, b3);81    System.out.println(nameAddition + ": " + a7 + " op " + b3 + " = " + result10);82}
    outputAddition: 7 op 3 = 10
  5. result ← 256, hello ← ⟨FunctionalInterfaceDemo lambda H⟩, formal ← ⟨FunctionalInterfaceDemo lambda I⟩

    pass 2 of 2
    41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter47    Greeter hello→ ⟨FunctionalInterfaceDemo lambda H⟩ = name -> "Hello, " + name + "!";48    System.out.println(hello.greet("World"));49    50    // Multi-line body51    Greeter formal→ ⟨FunctionalInterfaceDemo lambda I⟩ = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface79static void applyOperation(String namePower, int a2, int b8, Calculator calc⟨FunctionalInterfaceDemo lambda J⟩) {80    int result→ 256 = calc.calculate(a2, b8);81    System.out.println(namePower + ": " + a2 + " op " + b8 + " = " + result256);82}
    outputPower: 2 op 8 = 256
    
    === Lambda Variations ===
    Hello, World!
  6. supplier ← ⟨FunctionalInterfaceDemo lambda K⟩

    54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier→ ⟨FunctionalInterfaceDemo lambda K⟩ = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}
    outputDear Guest, welcome!
    Sample message at 1736937000000
    
    === @FunctionalInterface ===
    @FunctionalInterface annotation:
    - Documents intent
    - Compiler enforces single abstract method
    - Enables lambda usage
    
    Common built-in functional interfaces:
    - Runnable: () -> void
    - Comparator<T>: (T, T) -> int
    - Consumer<T>: (T) -> void
    - Supplier<T>: () -> T
    - Function<T, R>: (T) -> R
    - Predicate<T>: (T) -> boolean
  1. add1 ← ⟨FunctionalInterfaceDemo$1 A⟩

    3public class FunctionalInterfaceDemo {4    public static void main(String[] args) {5        System.out.println("=== Functional Interface ===\n");6        7        // Traditional: Anonymous inner class8        Calculator add1→ ⟨FunctionalInterfaceDemo$1 A⟩ = new Calculator() {9            @Override10            public int calculate(int a, int b) {11                return a + b;12            }13        };14        15        System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));
    output=== Functional Interface ===
  2. @Override public int calculate(int a, int b)

    8Calculator add1 = new Calculator() {9    @Override10    public int calculate(int a5, int b3) {11        return a5 + b3;12    }
  3. add2 ← ⟨FunctionalInterfaceDemo lambda B⟩, subtract ← ⟨FunctionalInterfaceDemo lambda C⟩

    15System.out.println("Anonymous class: 5 + 3 = " + add1.calculate(5, 3));1617// Modern: Lambda expression18Calculator add2→ ⟨FunctionalInterfaceDemo lambda B⟩ = (a, b) -> a + b;1920System.out.println("Lambda: 5 + 3 = " + add2.calculate(5, 3));2122System.out.println("\n=== Multiple Operations ===");2324// Different operations, same interface25Calculator subtract→ ⟨FunctionalInterfaceDemo lambda C⟩ = (a, b) -> a - b;26Calculator multiply→ ⟨FunctionalInterfaceDemo lambda D⟩ = (a, b) -> a * b;27Calculator divide→ ⟨FunctionalInterfaceDemo lambda E⟩ = (a, b) -> a / b;28Calculator max→ ⟨FunctionalInterfaceDemo lambda F⟩ = (a, b) -> a > b ? a : b;2930int x→ 10 = 10;31int y→ 2 = 2;32System.out.println(x10 + " + " + y2 + " = " + add2.calculate(x, y));33System.out.println(x10 + " - " + y2 + " = " + subtract.calculate(x, y));34System.out.println(x10 + " * " + y2 + " = " + multiply.calculate(x, y));35System.out.println(x10 + " / " + y2 + " = " + divide.calculate(x, y));36System.out.println("max(" + x10 + ", " + y2 + ") = " + max.calculate(x, y));3738System.out.println("\n=== Passing Lambda to Method ===");3940// Pass behavior as parameter41applyOperation("Addition", 7, 3, (a, b) -> a + b);42applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));
    outputAnonymous class: 5 + 3 = 8
    Lambda: 5 + 3 = 8
    
    === Multiple Operations ===
    10 + 2 = 12
    10 - 2 = 8
    10 * 2 = 20
    10 / 2 = 5
    max(10, 2) = 10
    
    === Passing Lambda to Method ===
  4. result ← 10

    pass 1 of 2
    40    // Pass behavior as parameter41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter47    Greeter hello = name -> "Hello, " + name + "!";48    System.out.println(hello.greet("World"));49    50    // Multi-line body51    Greeter formal = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface79static void applyOperation(String nameAddition, int a7, int b3, Calculator calc⟨FunctionalInterfaceDemo lambda G⟩) {80    int result→ 10 = calc.calculate(a7, b3);81    System.out.println(nameAddition + ": " + a7 + " op " + b3 + " = " + result10);82}
    outputAddition: 7 op 3 = 10
  5. result ← 256, hello ← ⟨FunctionalInterfaceDemo lambda H⟩, formal ← ⟨FunctionalInterfaceDemo lambda I⟩

    pass 2 of 2
    41    applyOperation("Addition", 7, 3, (a, b) -> a + b);42    applyOperation("Power", 2, 8, (a, b) -> (int) Math.pow(a, b));43    44    System.out.println("\n=== Lambda Variations ===");45    46    // Single parameter47    Greeter hello→ ⟨FunctionalInterfaceDemo lambda H⟩ = name -> "Hello, " + name + "!";48    System.out.println(hello.greet("World"));49    50    // Multi-line body51    Greeter formal→ ⟨FunctionalInterfaceDemo lambda I⟩ = name -> {52        String title = "Dear " + name;53        return title + ", welcome!";54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}7778// Method accepting functional interface79static void applyOperation(String namePower, int a2, int b8, Calculator calc⟨FunctionalInterfaceDemo lambda J⟩) {80    int result→ 256 = calc.calculate(a2, b8);81    System.out.println(namePower + ": " + a2 + " op " + b8 + " = " + result256);82}
    outputPower: 2 op 8 = 256
    
    === Lambda Variations ===
    Hello, World!
  6. supplier ← ⟨FunctionalInterfaceDemo lambda K⟩

    54    };55    System.out.println(formal.greet("Guest"));56    57    // No parameters58    MessageSupplier supplier→ ⟨FunctionalInterfaceDemo lambda K⟩ = () -> "Sample message at " + 1736937000000L;59    System.out.println(supplier.get());60    61    System.out.println("\n=== @FunctionalInterface ===");62    System.out.println("""63    @FunctionalInterface annotation:64    - Documents intent65    - Compiler enforces single abstract method66    - Enables lambda usage67    68    Common built-in functional interfaces:69    - Runnable: () -> void70    - Comparator<T>: (T, T) -> int71    - Consumer<T>: (T) -> void72    - Supplier<T>: () -> T73    - Function<T, R>: (T) -> R74    - Predicate<T>: (T) -> boolean75    """);76}
    outputDear Guest, welcome!
    Sample message at 1736937000000
    
    === @FunctionalInterface ===
    @FunctionalInterface annotation:
    - Documents intent
    - Compiler enforces single abstract method
    - Enables lambda usage
    
    Common built-in functional interfaces:
    - Runnable: () -> void
    - Comparator<T>: (T, T) -> int
    - Consumer<T>: (T) -> void
    - Supplier<T>: () -> T
    - Function<T, R>: (T) -> R
    - Predicate<T>: (T) -> boolean

@FunctionalInterface ensures single abstract method. Use with lambdas.

functional interface Interface with one abstract method. Can be implemented with lambda expression.

Exercise: Practical.java

Build a plugin system using interfaces