Bài tập Java OOP: tạo lớp Point và PolyLine | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points


Create a Polyline class and a Point class like the following class diagram:

To make it easier to understand the above class diagram, you need to understand what PolyLine is. PolyLine is a set of straight lines created by connecting two consecutive points together. For example, a PolyLine with coordinates of points [(0, 1), (1, 2), (1, 0), (2, 3), (3, 1), (4, 2)] looks like as follows:

Explain the class diagram:

Point class

  • This class is used for storing information about a point in a two-dimensional coordinate system.
  • x and y attributes describe the abscissa and ordinate of a point.
  • Point(x: int, y: int) is the parameter constructor used for initializing values to x and y.
  • setX(), getX(), setY(), getY() are setter and getter.

PolyLine class

  • points is an attribute that stores information about points in PolyLine, the data type of this attribute is List
  • PolyLine() is a parameter constructor which is used for initializing an empty ArrayList for points.
  • PolyLine(points: List<Point) is a parameter constructor which is used for initializing values to ponits.
  • appendPoint(point: Point) and appendPoint(x: int, y: int) methods are used for adding a point to the end of points.
  • getLength() method is used for getting the length of PolyLine. For example, if points = [(1, 1), (2, 3), (3, 0), (4, 2)] (see the illustration below),

    the getLength() method returns the following result 7.63441361516796.

A program to test PolyLine class:

public class Entry {
	public static void main(String[] args) {
		PolyLine polyLine = new PolyLine();
		polyLine.appendPoint(new Point(1, 1));
		polyLine.appendPoint(new Point(2, 3));
		polyLine.appendPoint(3, 0);
		polyLine.appendPoint(4, 2);

When the above code is compiled and executed, it produces the following result:


Note: CodeLearn accepts numerical error less than 0.000001


Code sample:

File Point.java

public class Point {
	private int x;
	private int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;

	public void setX(int x) {
		this.x = x;

	public int getX() {
		return x;

	public void setY(int y) {
		this.y = y;

	public int getY() {
		return y;

File PolyLine.java