Method Overriding -Java

Program:
class rectangle
{
    int dim1,dim2;
    double s;
    rectangle(int a,int b)
    {
        dim1=a;
        dim2=b;
    }
    void area()
    {
        s=dim1*dim2;
        System.out.println("Area of rectangle:"+s);
    }
}
class triangle extends rectangle
{
    triangle(int a,int b)
    {
        super(a,b);
    }
    void area()
    {
        s=(dim1*dim2)/2;
        System.out.println("Area of triangle="+s);
    }
}
class circle extends rectangle
{
    public circle(int a)
    {
        super(a,a);
    }
    void area()
    {
        s=3.14*dim1*dim1;
        System.out.println("Area of circle="+s);
    }
}
class ovriding
{
    public static void main(String args[])
    {
        rectangle x=new rectangle(3,4);
        triangle y=new triangle(3,4);
        circle z=new circle(10);
        rectangle p;
        p=x;
        p.area();
        p=y;
        p.area();
        p=z;
        p.area();
    }
}
Output:
nn@linuxmint ~ $ javac ovriding.java
nn@linuxmint ~ $ java ovriding
Area of rectangle:12.0
Area of triangle=6.0
Area of circle=314.0
nn@linuxmint ~ $

2 comments:

Related Posts Plugin for WordPress, Blogger...