In this lesson, you will learn
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.
interface interface-name2 extends interface-name1
{
// code
}

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());
}
}
Drawing Circle
Circle Area: 78.53981633974483
Drawing Sphere
Sphere Volume: 392.6990816987241
good
You must be logged in to submit a review.