Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Extending Interfaces in Java

In this lesson, you will learn

  • Extending Interface
  • Examples: Extending Interface

 

Extending Interfaces

1. In Java, interfaces can extend one or more other interfaces.

2. When an interface extends another interface, it inherits the abstract methods from the parent interface(s).

Note: A class implementing the child interface must provide implementations for all inherited abstract methods.

 

Syntax

interface interface-name2 extends interface-name1
{
     // code
}

 

Example: Extending Interfaces

 

package ch10.l5;

interface Shape {
    void draw(); // Common method to all shapes
}

interface TwoDShape extends Shape {
    double calculateArea(); // Specific to 2D shapes
}

interface ThreeDShape extends Shape {
    double calculateVolume(); // Specific to 3D shapes
}

//Circle Class (Implements TwoDShape)
class Circle implements TwoDShape {
    private double radius;

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

    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    }

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

//Sphere Class (Implements ThreeDShape)
class Sphere implements ThreeDShape {
    private double radius;

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

    @Override
    public void draw() {
        System.out.println("Drawing Sphere");
    }

    @Override
    public double calculateVolume() {
        return (4/3) * Math.PI * Math.pow(radius, 3);
    }
}

public class ExtendingInterface {

	public static void main(String[] args) {
		TwoDShape circle = new Circle(5);
        ThreeDShape sphere = new Sphere(5);

        circle.draw();
        System.out.println("Circle Area: " + circle.calculateArea());

        sphere.draw();
        System.out.println("Sphere Volume: " + sphere.calculateVolume());
	}
}

Output

Drawing Circle
Circle Area: 78.53981633974483
Drawing Sphere
Sphere Volume: 392.6990816987241

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

23/03/2025

good

 

 

Submit a Review