gpt4 book ai didi

java - 从另一个类(java)访问数据?

转载 作者:行者123 更新时间:2023-12-01 18:14:19 25 4
gpt4 key购买 nike

我创建了一个“父”类(不确定这是否是正确的术语),它代表 3d 空间中的一个点,如下所示:

public class Point3d {

private double xCoord;
private double yCoord;
private double zCoord;


public Point3d(double x,double y, double z ){
xCoord = x;
yCoord = y;
zCoord = z;
}

public Point3d() {
this (0,0,0);
}


public double getxCoord() {
return xCoord;
}


public double getyCoord() {
return yCoord;
}



public double getzCoord() {
return zCoord;
}

public void setX(double val){
xCoord= val;

}
public void setY(double val){
yCoord= val;
}
public void setZ(double val){
zCoord= val;
}

}

我有两个类定义了两个不同的点(x,y,z)第一类:

package threedimpoint;

public class FirstPoint {

public static void main(String[] args) {

Point3d frst = new Point3d();

frst.setX(0);
frst.setY(0);
frst.setZ(0);

System.out.println("(" + frst.getxCoord() + "," + frst.getyCoord() + "," + frst.getzCoord() + ")");



}

}

二等

package threedimpoint;

public class Secondpoint {

public static void main(String[] args) {

Point3d secnd = new Point3d();

secnd.setX(2);
secnd.setY(12);
secnd.setZ(24);

System.out.println("(" + secnd.getxCoord() + "," + secnd.getyCoord() + "," + secnd.getzCoord() + ")");

}

}

现在我希望创建一个新类,它获取的信息是 x,y,z 坐标从第一类(公共(public)类第一点)以及从第二类(公共(public)类第二点)

并用它来计算两点之间的距离。

如何在新类(class)中访问该信息?

最佳答案

如果要计算两点之间的距离,可以在类Point3d中创建一个函数。例如:

public class Point3d {

private double xCoord;
private double yCoord;
private double zCoord;


public Point3d(double x,double y, double z ){
xCoord = x;
yCoord = y;
zCoord = z;
}

public double calucateDistance(Point3d compareObj)
{
// ......
}
//......
}

然后你只需要创建一个测试类,在测试类中你可以创建两个Point3d实例,例如:

public class Test{

public static void main(String[] args) {

Point3d first = new Point3d();
first .setX(0);

first .setY(0);

first .setZ(0);

Point3d second = new Point3d();

second.setX(2);

second.setY(12);

second.setZ(24);

double result = first.calucateDistance(second);

}
}

关于java - 从另一个类(java)访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586223/

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