In: Computer Science
java
create a class for triangle and also driver(area and perimeter)
also write its getters and setters
for the right triangle
// RightTriangle.java : Java class to represent a right angled
triangle
public class RightTriangle {
// variables to store the base and height of the
triangle
private double base;
private double height;
// default constructor to set base and height to
0
public RightTriangle()
{
this(0,0);
}
// parameterized constructor to set the base and
height of the triangle to the passed arguments
public RightTriangle(double base, double height)
{
this.base = base;
this.height = height;
}
// setters
// method to set the height of the triangle
public void setHeight(double height)
{
this.height = height;
}
// method to set the base of the triangle
public void setBase(double base)
{
this.base = base;
}
// getters
// method to return the height of the triangle
public double getHeight()
{
return height;
}
// method to return the base of the triangle
public double getBase()
{
return base;
}
// method to compute and return the area of the
triangle
public double area()
{
return (base*height)/2;
}
// method to compute and return the perimeter of the
triangle
public double perimeter()
{
return(base+height+Math.sqrt(Math.pow(base, 2) + Math.pow(height,
2)));
}
}
//end of RightTriangle.java
// RightTriangleDriver.java : Driver program to test the RightTriangle class
public class RightTriangleDriver {
public static void main(String[] args) {
// test the RightTriangle
class
// create an object of
RightTriangle class
RightTriangle t1 = new
RightTriangle(3,4);
// display its bae, height , area
and perimeter
System.out.println("Base :
"+t1.getBase());
System.out.println("Height :
"+t1.getHeight());
System.out.println("Area :
"+t1.area());
System.out.println("Perimeter :
"+t1.perimeter());
}
}
//end of RightTriangleDriver.java
Output: