0

This is not my piece of code, but I would be interested to know something.

how to create, for example, an object of the triangle class?There, an array of the lengths of the sides of the triangle is passed as a parameter. But I do not know how to do it.Even if the array is registered in the main. Please tell me how to do it, I will be very grateful.

(I'll figure out how to do this with keyboard input later on my own.so far, only this question.)

  public class Polygon {
    int sideLengths[];
    int numSides =0;

    public Polygon(int [] lengths){
      sideLengths = lengths;
      numSides = lengths.length;
    }
  
    public int perimeter() {
  //compute perimeter
      int sum = 0;
      for (int i = 0 ; i <  sideLengths.length ;i++) {
        sum += sideLengths[i];
      }
      return sum;
    }

    //No area method.
  }

  public class Triangle extends Polygon {

    public Triangle(int [] lengths) {
      super(lengths);  //duper
      numSides = 3;
    }
    public Triangle () {
      this(new int[3]);
    }
    //No perimeter needed

    public double area (){
      double s = perimeter()/2;
      //Heron's formula
      return Math.sqrt(s*(s- sideLengths[0])*(s- sideLengths[1])*(s - sideLengths[2]));
    }
  }

Upd:I figured out how to call the perimeter method for an object of the polygon class.But how to do this for a triangle?

Vs_De_S
  • 155
  • 1
  • 6

1 Answers1

1

To create an instance of the Triangle class with your ownw lengths you simply need to invoke the Triange class constructor with the lengths you want to give it.

Example:

int[] lengths = new int[]{2, 2, 3};
Triangle triangle = new Triangle(lengths);
MrBorder
  • 359
  • 3
  • 8
  • Well, thank you, could you tell me how to call the methods for calculating the area and perimeter for the created object? – Vs_De_S Oct 01 '21 at 06:00
  • I understand that I have to write the applied method to some new variable in order to output it later, but how do I apply these methods to our object? – Vs_De_S Oct 01 '21 at 06:02
  • If you want to apply the perimeter method to it simply invoke it on our object like so: `int perimeter = triangle.perimeter();` – MrBorder Oct 01 '21 at 19:34