Lab 11: Polymorphism 1. Two Dimensional Shape a. circle b. square c. triangle Ba
ID: 3554446 • Letter: L
Question
Lab 11: Polymorphism
1. Two Dimensional Shape
a. circle
b. square
c. triangle
Based on the above hierarchy, please define classes as following:
TwoDimensionalShape:
Member functions: pure virtual function for GetArea
Circle: Private data member: radius
Member function: constructor, GetArea
Square: Private data member: length
Member function: constructor, GetArea
Triangle: Private data members: base and height
Member function: constructor, GetArea
Each TwoDimensionalShape should cotain a virtual function GetArea to calculate the area of the shape. Use the following main function to test your classes.
int main()
{
Circle c(10);
Square s(10);
Triangle t(10,5);
c.GetArea(); // will display
Explanation / Answer
interface TwoDimensionalShape {
int getArea();
}
class Circle implements TwoDimensionalShape{
private int radius;
public Circle(int radius) {
this.radius=radius;
}
public int getArea(){
return (int) (Math.PI*radius*radius);
}
}
class Square implements TwoDimensionalShape{
private int length;
public Square(int length) {
this.length=length;
}
public int getArea(){
return (int) (length*length);
}
}
class Triangle implements TwoDimensionalShape{
private int base;
private int height;
public Triangle(int base, int height) {
this.base=base;
this.height=height;
}
public int getArea(){
return (int) (base*height)/2;
}
}
public class TestShape{
public static void main(String[] args) {
}
private int main1(){
int areaCircle = new Circle(10).getArea();
System.out.println("Area of circle is " + areaCircle);
int areaSquare = new Square (10).getArea();
System.out.println("Area of Square is " + areaSquare);
int areaTriangle = new Triangle(10,5).getArea();
System.out.println("Area of Triangle is " + areaTriangle);
TwoDimensionalShape shape[] = { new Circle(5), new Square(5), new Triangle(20,5)};
return 0;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.