Write a Java public class named Trapezoid.java which has three private attribute
ID: 3686601 • Letter: W
Question
Write a Java public class named Trapezoid.java which has three private attributes: private double base1, private double base2, and private double height. In the class, include a default constructor, a constructor with double parameters base1, base2, and height. Also write and include the accessor and setter methods getHeight( ), setHeight (double height), getBase1( ), setBase1 (double base1), getBase2( ), setBase2 (double base2)and a method called computeArea ( ) which computes the area of a given Trapezoid according to the following formula:
areaTrapezoid = .5 * height * (base1 + base2);
Using the Trapezoid class created above, write a Java test class program named TrapezoidTest.java which will instantiate (create) two new Trapezoid objects trap1 & trap2. The first Trapezoid, trap1, will have a height of 50, and base1 will be 30 and base2 will be 70. For Trapezoid, trap2, use any values for the height, base1, and base2. TrapezoidTest.java will print the height, base1, base2 , and the area of both Trapezoids using the setter, getter, and computeArea methods from the Trapezoid class above.
Note: In the figure above, “a” is base1 and “b” is base2
Explanation / Answer
public class Trapezoid {
private double base1;
private double base2;
private double height;
public Trapezoid() {
base1=base2=height = 0;
}
public Trapezoid(double base1, double base2, double height) {
this.base1 = base1;
this.base2 = base2;
this.height = height;
}
public double getBase1() {
return base1;
}
public double getBase2() {
return base2;
}
public double getHeight() {
return height;
}
public void setBase1(double base1) {
this.base1 = base1;
}
public void setBase2(double base2) {
this.base2 = base2;
}
public void setHeight(double height) {
this.height = height;
}
public double computeArea(){
return .5 * height * (base1 + base2);
}
}
public class TrapezoidTest {
public static void main(String[] args) {
Trapezoid trap1 = new Trapezoid(30, 70, 50);
Trapezoid trap2 = new Trapezoid(20, 35, 40);
System.out.println("Trapezoid 1: ");
System.out.println(" Height: "+trap1.getHeight());
System.out.println(" Base1: "+trap1.getBase1());
System.out.println(" Base2: "+trap1.getBase2());
System.out.println(" Area: "+trap1.computeArea());
System.out.println();
System.out.println("Trapezoid 2: ");
System.out.println(" Height: "+trap2.getHeight());
System.out.println(" Base1: "+trap2.getBase1());
System.out.println(" Base2: "+trap2.getBase2());
System.out.println(" Area: "+trap2.computeArea());
}
}
/*
Output:
Trapezoid 1:
Height: 50.0
Base1: 30.0
Base2: 70.0
Area: 2500.0
Trapezoid 2:
Height: 40.0
Base1: 20.0
Base2: 35.0
Area: 1100.0
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.