Create an abstract class Shape and the derived classes Square, Triangle and Circle. Write a
java program to display area of different shapes.
public abstract class Shape {
public abstract double displayArea();
}
public class Circle extends Shape {
int radius;
public Circle(int radius) {
this.radius = radius;
}
@Override
public double displayArea() {
return Math.PI * Math.pow(radius, 2);
}
}
public class Square extends Shape{
int side;
public Square(int side) {
this.side = side;
}
@Override
public double displayArea() {
return Math.pow(side, 2);
}
}
public class Triangle extends Shape{
int a;
int b;
int c;
public Triangle(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double displayArea() {
double sp = (a + b + c) / 2.0; // Semiperimeter
return Math.sqrt(sp * (sp - a) * (sp - b) * (sp - c)); // Heron's formula
}
}
Comments
Leave a comment