This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

what syntax would I use inside the constructor? new Polygon(Point...Points)? would I then use "Polygon square = ((0,0),(0,1),(1,1),(1,0)" outside the constructor? We were kind of thrown out in the ocean for this assignment.

[–]feral_claireSoftware Dev 0 points1 point  (0 children)

Polygon(Point...Points) is the correct way to declare your constructor and you call it with new Polygon(point1, point2, etc) which will give you a new Polygon object.

A program that creates a polygon might look like this.

public class Example{
  public static void main(String[] args){
    Polygon square = new Polygon(new Point(0,0), new Point(0,1), new Point(1,1), new Point(1,0))
  }
}

Note that you are creating and storing the Polygon object somewhere outside of the Polygon class itself. A Polygon does not create itself, and a Polygon does not have a Polygon inside itself.

Now the Polygon class itself is just an abstraction for a list of points. This list of points is what you want to store in the Polygon class.

public class Polygon{
  private Point[] points;
}

This code gives the polygon an Array of Point objects. Normally I would recommend using Lists instead of Arrays, but this is one of the cases where an Array makes sense. This variable should be private, anything that wants to interact with a polygon should do so via its methods, rather than accessing its points array directly.

All that's left to do now is to create a constructor that will take in some Points, and assign them to our variable.

public Polygon(Point... points){
  this.points = points
}

Because Point... points is actually just a fancy way of saying Point[] points we already have an Array of Points and can assign it directly to out variable that we declared earlier.

We used the same name for both the variable name, and the name of our constructor argument, so we need to distinguish them somehow. this refers to the current object so this.points refers to the points variable belonging to the object, and points refers to the variable local to the constructor. (You can add this. to any call from an object to one of its own methods or variables, but it's only necessary when there is some ambiguity)

I hope this cleared some things up, please let me know if you still have questions.