In: Computer Science
Code:
abstract class Shapes{ //creating an
abstract class of shape
abstract public double getArea();
//creating a abstract method
}
class Rectangle extends Shapes{ //Rectangle class inherites shapes Class
private double length=0;
//defining length variable
private double width=0;
//defining length variable
public Rectangle(double l,double
w){ //constructor with legth and width as
parameters
this.length =
l; //assignig the values to the variables
this.width = w;
}
public double
getArea(){ //implementing
the abstract function of parent class
double area = length *
width; // calculating area of rectangle
return
area; //returning area
}
}
class Circle extends Shapes{ //Circle extends
the Shapes class
private double radius=0;
//defining length variable
public Circle(double r){
//constructor with radius parameter
this.radius =
r; //assigning
radius
}
public double
getArea(){
//implementing the abstract function of parent class
double area = Math.PI *
radius * radius; // calculating
area of Circle
return
area; //returning area
}
}
class Triangle extends Shapes{
private double base = 0;
//defining base variable
private double height = 0; //defining height
variable
public Triangle(double b,double
h){ //constructor with legth and width as
parameters
this.base =
b; //assigning base of the
triangle
this.height =
h; //assigning height of the triangle
}
public double
getArea(){ //area
calculating fuction
double area = 0.5 * base
* height;
return
area; //returning the
area
}
}
public class TestClass{ //test class to
print the areas of the objects
public static void main (String[] args) {
Rectangle rect1 = new
Rectangle(2,3); //creating a rectanle object with
legth=2 and width=3
System.out.println("Area
of the Rectangle is :" + " "+rect1.getArea()); //printing the area
of the rectangle
Triangle tr1 = new
Triangle(2,6); //creating a
Triangle object with base=2 and height=6
System.out.println("Area
of the Triangle is :" + " "+tr1.getArea());
//printing the area of the Triangle
Circle c1 = new
Circle(4);
//creating a Circle object with radius 4
System.out.println("Area
of the Circle is :"+ " " +
c1.getArea()); //printing the area of
the Circle
}
}