Interfaces

 

Interfaces

 

// Interface

 

interface Shape

{

    public void printArea();

}

 

// Rectangle class

class Rectangle implements Shape

{

    double dim1, dim2;

   

    Rectangle(double length, double breadth)

    {

        dim1 = length;

        dim2 = breadth;

    }

 

    public void printArea()

    {

        double area = dim1 * dim2;

        System.out.printf("Area of Rectangle = %.2f%n", area);

    }

}

 

// Triangle class

class Triangle implements Shape

{

    double dim1, dim2;

   

    Triangle(double base, double height)

    {

        dim1 = base;

        dim2 = height;

    }

 

    public void printArea()

    {

        double area = 0.5 * dim1 * dim2;

        System.out.printf("Area of Triangle = %.2f%n", area);

    }

}

 

// Circle class

class Circle implements Shape

{

    double dim1;

   

    Circle(double radius)

    {

        dim1 = radius;

    }

 

    public void printArea()

    {

        double area = Math.PI * dim1 * dim1;

        System.out.printf("Area of Circle = %.2f%n", area);

    }

}

 

public class Demo_Interface

{

    public static void main(String as[])

    {

        Rectangle r = new Rectangle(10, 5);

        r.printArea();

 

        Triangle t = new Triangle(6, 8);

        t.printArea();

 

        Circle c = new Circle(7);

        c.printArea();

    }

}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu