In: Computer Science
Java
Apply inheritance to write a super class and subclass to compute the triangle area and the surface area of triangular pyramid, respectively. Assume that each side has the same length in the triangle and triangular pyramid. You need also to override toString() methods in both of super class and subclass so they will return the data of an triangle object and the data of the pyramid object, respectively. Code a driver class to test your classes by creating at least two objects with hard-coded data and display the results of the calculations.
Use of meaningful names for variables, classes, and methods and meaningful comments.
JAVA CODE:
class Triangle
{
private double length;
public Triangle()
{
this.length = 0.00;
}
public Triangle(double length)
{
this.length = length;
}
// Setter and getter methods
public double get_the_Length()
{
return length;
}
public void set_the_Length(double length)
{
this.length = length;
}
// Create a to_string() method
@Override
public String toString()
{
return "Triangle [length=" + length + "]";
}
// Create a method named Surface_Area()
public double Surface_Area()
{
return Math.sqrt(3) / 2 * Math.pow(this.get_the_Length(), 2);
}
}
class Tri_Vertebral extends Triangle
{
private double height;
public Tri_Vertebral()
{
super(0);
this.height = 0.00;
}
// Create a parameter constructor.
public Tri_Vertebral(double length, double height)
{
super(length);
this.height = height;
}
// Getter and setter methods
public double get_the_Height()
{
return height;
}
public void set_the_Height(double height)
{
this.height = height;
}
public double totalFaceArea()
{
return 3 / 2 * this.get_the_Length() * this.get_the_Height();
}
// Create a method named totalSurface_Area
public double totalSurface_Area()
{
return this.Surface_Area() + 3 * this.totalFaceArea();
}
// the toString method is as follows:
@Override
public String toString()
{
return "Tri_Vertebral [height=" + height + "," + super.toString() +
"]";
}
}
//Driver code
public class Triangle_Test
{
// Create a main method.
public static void main(String[] args)
{
// Create an object for the class named Triangle
Triangle t1 = new Triangle(15);
System.out.println("Area of traingle:");
System.out.println(t1.Surface_Area());
System.out.println("Traingle using tostring method:");
System.out.println(t1.toString());
// Create an object for the class named Tri_Vertebral
Tri_Vertebral tp = new Tri_Vertebral(15, 20);
System.out.println("Surface area of triangle pyramid");
System.out.println(tp.totalSurface_Area());
System.out.println("Tri_Vertebral using tostring method:");
System.out.println(tp.toString());
}
}
OUTPUT SCREENSHOT:
//Hope you understood the code and have a good day..Don't forget to give UPVOTE s it means a lot..THANKS:)