使用多个类时构造函数未定义

我有一个问题。第一次,我在JAVA中使用多个类。我这样做有些麻烦。我创建了一个班级,该班级将从另一个班级进行调用。我想创建一个Coordinate类型,顾名思义,它保存坐标。然后,我想移动这些坐标。到目前为止,代码如下:

public class Coordinate {
    double x;
    double y;

    Coordinate(){
        x=0;
        y=0;
    }

    public Coordinate(int x,int y){
        this.x = x;
        this.y = y;
        System.out.print(x);//TO TEST WHETHER IT DOES SOMETHING
    }

    Coordinate shiftCoordinate(int z,int w){
        this.x = x + z;
        this.y = y+ w;
        return new Coordinate(x,y);//ERROR: The constructor Coordinate(double,double) is undefined
    }


}

在指出的地方抛出错误。我不明白这个错误。在我的“主要”课程中,我做了以下事情:

void start() {

    Coordinate coordinate = new Coordinate();
    coordinate.x=3;
    coordinate.y=4; 
}

我希望它能打印3,但不会。我在哪里错了?

x4536453 回答:使用多个类时构造函数未定义

首先,您不使用mutiples类,只能使用一个Coordinate,但是您需要多个构造函数。

  1. 由于您的属性是double,因此需要一个需要该类型的构造函数,因此在编写new Coordinate(5,6)时会使用它

    public Coordinate(double x,double y) {
        this.x = x;
        this.y = y;
    }
    
  2. 如果您需要默认的构造函数(无参数),则在调用new Coordinate()

  3. 时将使用它
  4. 您想要一种从Coordinate实例转移的方法,您有以下两种方法:修改当前实例,但不要同时进行(就像您的代码一样)在最后两个对象具有相同的值是没有用的

    // modify current instance
    void shiftCoordinate(double z,double w) {
        this.x = x + z;
        this.y = y + w;
    }
    
    // return a new object
    Coordinate shiftCoordinate(double z,double w) {
        return new Coordinate(this.x + z,this.y + w);
    }
    

最后,您的代码使用没有args的默认构造函数,因此正常情况下您不会看到任何打印使用new Coordinate(3,4)来查看


经典构造函数也是,用于克隆实例的构造函数,它需要一个实例并创建一个具有相同值的新实例:

    public Coordinate(Coordinate clone) {
        this.x = clone.x;
        this.y = clone.y;
    }
,
public Coordinate(int x,int y){
    this.x = x;
    this.y = y;
    System.out.print(x);
}

此构造函数的参数为​​整数,因此您尝试传递双精度数。将构造函数更改为此:

public Coordinate(double x,double y){
    this.x = x;
    this.y = y;
    System.out.print(x);
}
本文链接:https://www.f2er.com/3121717.html

大家都在问