是否可以在Java中使用类的构造函数并将其声明为另一类的数据类型



如果我有一个构造函数,则称为point class Point:

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

我如何使用另一个称为Square并初始化点的类。例如,我想在正方形中初始化4点。我怎样才能做到这一点?

我不知道这是否有道理。但是,我尽了最大的努力...问我问题,以便我可以更好地解释。

您的方形类应具有这样的构造函数:

public Square(Point p1, Point p2, Point p3, Point p4) {
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
}

您这样初始化广场:

Square s = new Square(new Point(1,1), new Point(2,2), new Point(3,3), new Point(4,4));

如果要与点有一个 Square,请使其属性:

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())};
    }
}

最新更新