class
figure
{
double dim1,dim2;
figure(double x,double y)
{
dim1=x;
dim2=y;
}
double area()
{
System.out.println("Area
undefined");
return 0;
}
}
class
rectangle extends figure
{
rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Rectangle
Area");
return dim1*dim2;
}
}
class
triangle extends figure
{
triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("Triangle
Area");
return dim1*dim2/2;
}
}
class
run
{
public static void main(String[]
args)
{
figure obj=new figure(10,10);
rectangle obj1=new rectangle(9,5);
triangle obj2=new triangle(10,8);
figure a; //a is a reference of type figure(super
class)
a=obj1; //a refers to object of
rectangle(sub class)
System.out.println("Area="+a.area());
a=obj; //a refers to object of figure
System.out.println("Area="+a.area());
a=obj2; //a refers to object of triangle
System.out.println("Area="+a.area());
}
}
O/P: Rectangle Area
Area=45.0
Area undefined
Area=0.0
Triangle Area
Area=40.0
No comments:
Post a Comment