Midterm 2-Solution
Midterm 2-Solution
Exercise 1: (2 marks)
4- A new class is created that has the features from the already existing class.
Based on inheritance and override methods concept, write a Java code that represents the
following class:
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+” its
area = “+getArea()+” and its pemieter = “+getperimeter();
}
}
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+”
its area = “+getArea()+” and its pemieter = “ +getperimeter();
}
}
package Ex2;
public class TestShape {
public static void main(String[] args) {
//1-Create the two objects
Shape R = new Rectangle (6.5, 5.2);
Shape T = new Triangle (3, 2.5);
//Print the information of each object along with their area and Premiter
System.out.println("the first shape is "+R.toString);
System.out.println("the second shape is "+T.toString);
}
}