Java Program to Make Shape as an Interface and Implement it using Circle and Rectangle Class


Java logo and symbol, meaning, history, PNG

This is a Java Program to Make Shape as an Interface and Implement it using Circle and Rectangle  Class.

Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Here we make interface as Shape with two methods as input() and area() which are implemented by further two classes as circle and rectangle who implements the interface Shape.

Here is the source code of the Java Program to Make Shape as an Interface and Implement it using Circle and Rectangle Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.


PROGRAM:

interface Shape{
    public double area();
}
class Circle implements Shape{
    double radius;
    public Circle(double r){
        radius = r;
    }
    public double area(){
        return 3.14 * radius * radius;
    }
}
class Rectangle implements Shape{
    double length;
    double breadth;
    public Rectangle(double l, double b){
        length = l;
        breadth = b;
    }
    public double area(){
        return length * breadth;
    }
}
class InterfaceDemo{
    public static void main(String args[]){
        Circle c = new Circle(2.5);
        System.out.println("Area of circle: " + c.area());
        Rectangle r = new Rectangle(5.0, 2.5);
        System.out.println("Area of rectangle: " + r.area());
    }
}
OUTPUT:

$ javac Demo.java
$ java  Demo
 
Area of circle:19.62
Area of rectangle:12.5
Previous Post Next Post