如果我在类 Point 中有一个名为 Point 的构造函数:
public Point(double x, double y) {
this.x = x;
this.y = y;
}
我如何使用另一个名为 Square 的类并初始化这些点。例如,我想在一个正方形中初始化 4 个点。我怎样才能做到这一点?
我不知道这是否有意义。但是,我尽力了……问我问题,以便我能更好地解释。
如果我在类 Point 中有一个名为 Point 的构造函数:
public Point(double x, double y) {
this.x = x;
this.y = y;
}
我如何使用另一个名为 Square 的类并初始化这些点。例如,我想在一个正方形中初始化 4 个点。我怎样才能做到这一点?
我不知道这是否有意义。但是,我尽力了……问我问题,以便我能更好地解释。
你的 Square 类应该有一个这样的构造函数:
public Square(Point p1, Point p2, Point p3, Point p4) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
}
你像这样初始化你的 Square:
Square s = new Square(new Point(1,1), new Point(2,2), new Point(3,3), new Point(4,4));
如果您想拥有一个Square
with for 点,请将它们设为属性:
class Square {
Point p1, p2, p3, p4;
public Square() {
p1 = new Point(0,0);
p2 = new Point(0,0);
p3 = new Point(0,0);
p4 = new Point(0,0);
}
}
当然,还有无数其他方法来定义和使用它。这将主要取决于您的课程/程序设计您应该选择什么。
我没有看到问题。您Square
只需拥有四个类型的成员,Point
这些成员将使用通常的new
-syntax 进行初始化:
class Square {
Point topLeft;
public Square() {
topLeft = new Point(0,0);
}
}
你可以做
public Shape(Point... points) {
this.points = points;
}
或者
public Quadrilateral(Point p1, Point p2, Point p3, Point p4) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
}
或者
public Square(double x, double y, double size) {
this.x = x;
this.y = y;
this.size = size;
}
我不确定我是否遵循,但如果你有一个像你说的构造函数,你可以简单地调用new Point(10.0, 15.0)
在指定的坐标处创建一个点。
也许你追求的是这样的东西?
class Square {
private Point upperLeftCorner;
private Point upperRightCorner;
private Point lowerLeftCorner;
private Point lowerRightCorner;
public Square(double x, double y, double size) {
upperLeftCorner = new Point(x, y);
lowerLeftCorner = new Point(x, y+size);
upperRightCorner = new Point(x+size, y);
lowerRightCorner = new Point(x+size, y+size);
}
}
你是这个意思吗?
java GeoTest
[{0.0,0.0}, {0.0,10.0}, {10.0,10.0}, {10.0,0.0}]
代码:
import java.util.Arrays;
public class GeoTest{
public static void main(String[] args){
System.out.println(Arrays.toString(new Square(new Point(0,0), new Point(10,10)).getCourners()));
}
}
class Point{
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString(){
return new String("{"+x+","+y+"}");
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
class Square {
private Point lowerLeft;
private Point upperRight;
/**
* Assuming x & y axis as follows:
* Lower left corner (x,y):0,0 -> upper right corner (x,y): n,n where n > 0
*/
public Square(Point lowerLeft, Point upperRight){
this.lowerLeft = lowerLeft;
this.upperRight = upperRight;
}
public Point[] getCourners(){
return new Point[]{lowerLeft, new Point(lowerLeft.getX(),upperRight.getY()),upperRight, new Point(upperRight.getX(), lowerLeft.getY())};
}
}