Java OOP example

// TestPolygon.java

// Represents a single point with x and y coordinates
class Point {

    int x, y;

    // Constructor to create a Point
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Converts the Point into a readable String
    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}


// Represents a polygon made up of multiple points
class Polygon {

    // Array to store the corners of the polygon
    Point[] points;

    // Constructor to create a Polygon
    Polygon(Point[] points) {
        this.points = points;
    }

    // Displays all the points of the polygon
    void displayPoints() {
        System.out.print("Polygon corners: ");

        // Loop through every Point in the array
        for (Point p : points) {
            System.out.print(p + " ");
        }

        System.out.println();
    }
}


// Factory class used to create Polygon objects
class ShapeFactory {

    // Creates and returns a Polygon from an array of Points
    public Polygon polygonFrom(Point[] corners) {

        // Create a new Polygon using the given corners
        Polygon polygon = new Polygon(corners);

        // Return the Polygon object
        return polygon;
    }
}


// Main class
public class TestPolygon {

    public static void main(String[] args) {

        // Create an array of Point objects
        Point[] corners = {
            new Point(0, 0),
            new Point(4, 0),
            new Point(4, 3),
            new Point(0, 3)
        };

        // Create an object of ShapeFactory
        ShapeFactory factory = new ShapeFactory();

        // Use polygonFrom() to create a Polygon
        Polygon myPolygon = factory.polygonFrom(corners);

        // Display the corners of the polygon
        myPolygon.displayPoints();
    }
}
// Output

Polygon corners: (0, 0) (4, 0) (4, 3) (0, 3)

Key concept:

Point[] corners
       ↓
factory.polygonFrom(corners)
       ↓
new Polygon(corners)
       ↓
Polygon myPolygon

So the polygonFrom() method is essentially responsible for creating and returning a Polygon object from the given points.