仔细阅读以下所给的代码,完善Point类,在Point类中覆盖Object的toString()和equals()方法,使得编译执行主类Test输出如下结果: public class Test{ public static void main(String[] args){ Point pt1=new Point(12,24,36); Point pt2=new Point(12,24,36); System.out.println("pt1:"+pt1); System.out.println("pt1.equals(pt2):"+ pt1.equals(pt2)); } } class Point{ private double x; private double y; private double z; public Point(){} public Point(double x,double y,double z){ this.x=x; this.y=y; this.z=z; } public double getX(){return this.x;} public void setX(double x){this.x=x;} public double getY(){return this.y;} public void setY(double y){this.y=y;} }
时间: 2023-06-23 12:08:06 浏览: 106
完善后的代码如下:
```
public class Test{
public static void main(String[] args){
Point pt1=new Point(12,24,36);
Point pt2=new Point(12,24,36);
System.out.println("pt1:"+pt1);
System.out.println("pt1.equals(pt2):"+ pt1.equals(pt2));
}
}
class Point{
private double x;
private double y;
private double z;
public Point(){}
public Point(double x,double y,double z){
this.x=x;
this.y=y;
this.z=z;
}
public double getX(){return this.x;}
public void setX(double x){this.x=x;}
public double getY(){return this.y;}
public void setY(double y){this.y=y;}
public double getZ(){return this.z;}
public void setZ(double z){this.z=z;}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + ", z=" + z + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
return false;
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z))
return false;
return true;
}
}
```
输出结果为:
```
pt1:Point [x=12.0, y=24.0, z=36.0]
pt1.equals(pt2):true
```
其中,Point类中覆盖了Object的toString()和equals()方法,toString()方法返回一个字符串,表示该点的x、y、z坐标值,equals()方法判断两个Point对象是否相等,如果它们的x、y、z坐标值都相等,则返回true,否则返回false。在测试主类Test中,创建了两个Point对象pt1和pt2,它们的坐标值都相等,因此调用equals()方法返回true。在输出pt1时,调用了Point类的toString()方法,返回了该点的x、y、z坐标值。
阅读全文