Q3: Write a complete Class called “Triangle”, which represents a mathematical
triangle. (10 points)
The structure has the following instance variables:
1. base – double value representing the base of a triangle
2. height – double value representing the height of the rectangle
The structure has the following methods
1. Constructor - This constructor takes two formal parameters representing the base and height respectively. The parameters are used to initialize the corresponding instance variables.
2. getBase - This method returns the base value.
3. getHeight - This method returns the height value.
4. setBase - This method updates the base value with the single parameter.
5. setHeight - This method updates the height value with the single parameter.
6. Area - This is a static method that takes as formal parameter a Triangle reference and returns a double representing the area of the triangle.
class Triangle {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase(){return base;}
public double getHeight(){return height;}
public void setBase(double base) {this.base =base;}
public void setHeight(double h) {height=h;}
public double getArea() {return 0.5 * base * height;}
}
Comments
Leave a comment