Q.No.2. Design an abstract class GeometricObject with lineColor as data member. GeometricObject must ensure that its children implement calcArea() method. [Marks : 03]
Design RectangleYourRegNo and CircleYourName Classes as children of GeometricObject class with overridden toString() method to return “Rectangle with w Width and h Height is drawn” OR “Circle with r Radius is drawn”. The attributes of Rectangle are length, width. The attribute of Circle is radius
Hint: Area of circle=πr2 , Area of rectangle= width*length
public class TestYourName {
static abstract class GeometricObject {
protected String lineColor;
public GeometricObject() {
this.lineColor = "black";
}
public GeometricObject(String lineColor) {
this.lineColor = lineColor;
}
public abstract float calcArea();
}
static class CircleYourName extends GeometricObject {
private int radius;
public CircleYourName (int radius) {
this.radius = radius;
}
public CircleYourName(int radius, String lineColor) {
super(lineColor);
this.radius = radius;
}
@Override
public float calcArea() {
return (float) (Math.PI * radius * radius);
}
@Override
public String toString() {
return "Circle with " + radius + " radius is drawn";
}
}
static class RectangleYourRegNo extends GeometricObject {
private int length;
private int width;
public RectangleYourRegNo (int length, int width) {
this.length = length;
this.width = width;
}
public RectangleYourRegNo(int length, int width, String lineColor) {
super(lineColor);
this.length = length;
this.width = width;
}
@Override
public float calcArea() {
return width * length;
}
@Override
public String toString() {
return "Rectangle with " + width + " width and " + length + " height is drawn";
}
}
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
CircleYourName circleYourName=new CircleYourName(5);
System.out.println(circleYourName.toString());
System.out.println("Area: "+circleYourName.calcArea());
CircleYourName circleYourName1=new CircleYourName(8,"Red");
System.out.println(circleYourName1.toString());
System.out.println("Area: "+circleYourName1.calcArea());
RectangleYourRegNo RectangleYourRegNo=new RectangleYourRegNo(3,9);
System.out.println(RectangleYourRegNo.toString());
System.out.println("Area: "+RectangleYourRegNo.calcArea());
RectangleYourRegNo RectangleYourRegNo1=new RectangleYourRegNo(8,5,"Blue");
System.out.println(RectangleYourRegNo1.toString());
System.out.println("Area: "+RectangleYourRegNo1.calcArea());
}
}
Comments
Leave a comment