Add the following constructor to your Line class:
public Line(int x1, int y1, int x2, int y2)
Constructs a new Line that contains the given two Points.
//package classes;
public class Line {
Point point1;
Point point2;
// initialize the line class with the constructor
public Line(Point Point1, Point point2) {
this.point1 = Point1;
this.point2 = point2;
}
// initialize the line class by passing the points
public Line(int x1,int y1,int x2,int y2) {
this.point1 = new Point(x1,y1);
this.point2 = new Point(x2,y2);
}
public Point getPoint1() {
return point1;
}
public Point getPoint2() {
return point2;
}
// override the tostring to print the points
public String toString() {
return "[" +point1.toString()+", " +point2.toString()+"]";
}
//this method return the slope of two points
public double getSlope() {
if(point1.getX() == point2.getX())
throw new IllegalArgumentException();
double slope = (double) (point2.getY() - point1.getY()) / (point2.getX() - point1.getX());
return slope;
}
public static void main(String[] args) {
Line line = new Line(3,2,9,8);
System.out.println("the string representation of the line is :"+line);
System.out.println("slope of the line is: " +line.getSlope());
}
}
Output:
the string representation of the line is :[(3,2), (9,8)]
slope of the line is: 1.0