Shape Exercise
Shape Exercise
Based on inheritance and override methods concept, write a Java code that represents the
following class:
Shape (abstract)
+Shapes()
+getPerimeter() :double(abstract).
+getArea():double(abstract)
+toString():string
+rectangle( double L, +Square (double S) +triangle (double Side, +Circle (double radius)
double W) double h)
+getArea():double +getArea():double
+getArea():double +getArea():double
+getPerimeter():double +getPerimeter():double
+getPerimeter():double +getPerimeter():double
+toString():string +toString():string
+toString():string +toString():string
Solution:
package Ex2;
public abstract class Shape {
public Shape(){
}
public abstract double getArea();
public abstract double getPerimeter();
public String toString(){
}
}
package Ex2;
public class Rectangle extends Shape {
double length, width;
public Rectangle(){
}
public Rectangle(double len, double br){
length = len;
width = br;
}
public double getArea(){
return length*width;
}
public double getperimeter(){
return 2*(length+width);
}
public String toString(){
return super.toString()+" Rectangle and its length = "+length+" and its width = "+width; }
}
package Ex2;
public class Square extends Shape {
double s;
public Square(){
}
public Square(double b){
s = b;}
public double getArea(){
return s*s;
}
public double getpremieter(){
return 4*s;
}
public String toString(){
return super.toString()+" Square and its side = "+s ; }
}
package Ex2;
public class Triangle extends Shape {
double side, height;
public Triangle(){
}
public Triangle(double b, double h){
side = b;
height = h;
}
public double getArea(){
return 0.5*side*height;
}
public double getpremieter(){
return 3*side;
}
public String toString(){
return super.toString()+" Triangle and its side = "+side+" and its height = "+height;
}
}
package Ex2;
public class Circle extends Shape {
double radius;
final static double PI = 3.141592564 ;
public Circle(){
}
public Circle (double r){
radius = r;}
public double getArea(){
return radius*radius*PI;
}
public double getpremieter(){
return 2*radius*PI;
}
public String toString(){
return super.toString()+" Circle and its radius = "+radius;
}
}
package Ex2;
public class TestShape {
public static void main(String[] args) {
//1-Create the four objects
Shape R = new Rectangle (4.5, 2);
Shape S=new Square (3.5);
Shape T = new Triangle (2.5, 3.2);
Shape C= new Circle( 5.5);
//Print the information of each object along with their area and Premiter
System.out.println("the first shape is "+R.toString()+” its area = “+R.getArea()+” and its
pemieter = “ + R.getperimeter());
System.out.println("the second shape is "+S.toString()+” its area = “+S.getArea()+” and its
pemieter = “ + S.getperimeter());
System.out.println("the third shape is "+T.toString()+” its area = “+T.getArea()+” and its
pemieter = “ + T.getperimeter());
System.out.println("the last shape is "+C.toString()+” its area = “+C.getArea()+” and its pemieter
= “ + C.getperimeter());
}
}