我正在尝试创建简单的对象,从单点对象分支到线对象(两个点),然后到三角形对象(三个点)。我了解如何创建点类,但在尝试分支到线类时,我对如何使用初始点类实际编写线类或三角形类有点困惑。我需要一些帮助才能从单点课程进入
我可以发布一些到目前为止我已经完成的代码。
我还读到那里已经有 java 几何类,但我想实际创建这些类来练习 OOP。
编辑---在下面添加代码
class Point
{
private double x;
private double y;
public Point()
{
x = 0.0;
y = 0.0;
}
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX()
{
return this.x;
}
public double getY()
{
return this.y;
}
public void setX(double x)
{
this.x = x;
}
public void setY(double y)
{
this.y = y;
}
public double distance(Point p)
{
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y)
* (this.y - p.y));
}
public String toString()
{
String s = "(" + x + ", " + y + ")";
return s;
}
public boolean equals(Point p)
{
double delta = 1.0e-18;
return (Math.abs(this.x - p.x) < delta)
&& (Math.abs(this.y - p.y) < delta);
}
//-----------------Line Class--------------------//
class Line
{
private Point p1;
private Point p2;
public Line()
{
p1 = new Point (0,0);
p2 = new Point (1,1);
}
public Line(double x1, double y1, double x2, double y2)
{
p1 = new Point (x1, y1);
p2 = new Point (x2, y2);
}
public Line(Point p, Point q)
{
p1 = new Point(p.getX(), p.getY());
p2 = new Point(q.getX(), q.getY());
}
public Point getP1()
{
return this.p1;
}
public Point getP2()
{
return this.p2;
}
public void setP1(double x, double y)
{
Point p1 = new Point(x, y);
this.p1 = p1;
}
public void setP2(double x, double y)
{
Point p2 = new Point(x, y);
this.p2 = p2;
}
public boolean isParallelY()
{
double delta = 1.0e-18;
return (Math.abs(p1.getX() - p2.getX()) < delta);
}
public boolean isParallelX()
{
double delta = 1.0e-18;
return (Math.abs(p1.getY() - p2.getY()) < delta);
}
public boolean isParallel (Line line)
{
if (this.Slope() == line.Slope())
return true;
else
return false;
}
public double Slope()
{
double inf = Double.POSITIVE_INFINITY;
if(isParallelY())
return inf;
return ((p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
}
public double xIntercept()
{
return -(p1.getY() / Slope() - p1.getX());
}
public double yIntercept()
{
return p1.getY() - (Slope() * p1.getX());
}
我现在仍在向线类添加方法,还没有开始使用三角形类(尽管我正在考虑创建一个 3 点而不是 3 条线的三角形。对于分支混乱,我很抱歉,我比较新。