Write an abstract class shape, which defines abstract method area. Derive class circle from shape. It has data member radius and implementation for area function. Derive class Triangle from shape. It has data members height, base and implementation for area function. Derive class Square from shape. It has data member side and implementation for area function. In main class, use dynamic method dispatch in order to call correct version of method.
Code:
Output:
Code:
abstract class Shape
{
abstract void area();
}
class Circle extends Shape
{
double radius;
void area()
{
System.out.println("\nArea of Circle: "+(3.14*radius*radius));
}
}
class Triangle extends Shape
{
double height,base;
void area()
{
System.out.println("Area of Triangle: "+((height*base)/2));
}
}
class Square extends Shape
{
double side;
void area()
{
System.out.println("Area of Square: "+(side*2));
}
}
class S6P1_Dynemic_Dispatch
{
public static void main(String args[])
{
Circle C1 = new Circle();
C1.radius = 4;
Triangle T1 = new Triangle();
T1.height = 5; T1.base = 11.4;
Square S1 = new Square();
S1.side = 23.5;
Shape S;
S = C1;
S.area();
S = T1;
S.area();
S = S1;
S.area();
}
}
Output:
No comments:
Post a Comment