gpt4 book ai didi

java - 在主方法中调用类的构造函数?

转载 作者:行者123 更新时间:2023-12-02 04:13:49 26 4
gpt4 key购买 nike

我已经阅读了其他一些问题,但似乎仍然不知道如何让我的问题工作,感谢任何帮助。下面给出了我到目前为止的代码。我希望能够调用 newPointParameters 来创建一个新类。

public class Lab4ex1 {
public static void main(String[] args) {
System.out.println("" + 100);

new newPointParameter(42,24);
}
class Point {
private double x = 1;
private double y = 1;

public double getx() {
return x;
}
public double gety() {
return y;
}
public void changePoint(double newx, double newy) {
x = newx;
y = newy;
}
public void newPointParameters(double x1, double y1) {
this.x = x1;
this.y = y1;
}
public void newPoint() {
this.x = 10;
this.y = 10;
}
public double distanceFrom(double x2, double y2) {
double x3 = x2 - this.x;
double y3 = y2 - this.y;
double sqaureadd = (y3 * y3) + (x3 * x3);
double distance = Math.sqrt(sqaureadd);
return distance;
}
}

}

最佳答案

因此,目前 newPointParameters 和 newPoint 都不是构造函数。相反,它们只是方法。为了使它们成为构造函数,它们需要与构造的类共享相同的名称

class Point {

private double x = 1;
private double y = 1;

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

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

然后,当您想创建一个新点时,只需执行以下操作

对于默认点

public class Lab4ex1 {

public static void main(String[] args) {
System.out.println("" + 100);

//this will create a new Point object, and call the Point() constructor
Point point = new Point();
}

对于带参数的点

public class Lab4ex1 {

public static void main(String[] args) {
System.out.println("" + 100);

//this will create a new Point object, and call the
//Point(double x, double y) constructor
Point point = new Point(10.0, 10.0);
}

关于java - 在主方法中调用类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33530892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com