JAVA/기초 프로그래밍
함수//클래스에서 오버라이딩하여 변수 값 비교하기 (*헷깔림)
웨이칭
2020. 6. 9. 19:29
문제 : 다음과 같은 실행결과를 얻도록 Point3D클래스의 equals()를 멤버변수인 x, y, z
의 값을 비교하도록 오버라이딩하고, toString()은 실행결과를 참고해서 적절히
오버라이딩하시오.
실행결과
[1,2,3]
[1,2,3]
p1==p2?false
p1.equals(p2)?true
Point3D
public class Point3D {
int x,y,z;
public Point3D(int x, int y, int z) {
this.x=x;
this.y=y;
this.z=z;
}
public Point3D() {
this(0,0,0);
}
public boolean equals(Object obj) {
/*
(1) 인스턴스변수 x, y, z를 비교하도록 오버라이딩하시오.
*/
Point3D pos = (Point3D)obj;
if(this.x == pos.x && this.y == pos.y && this.z == pos.z) {
return true;
}
return false;
}
@Override
public String toString() {
return "Point3D [x=" + x + ", y=" + y + ", z=" + z + "]";
}
}
Main
public class mainClass {
public static void main(String[] args) {
Point3D p1 = new Point3D(1,2,3);
Point3D p2 = new Point3D(1,2,3);
System.out.println(p1);
System.out.println(p2);
System.out.println("p1==p2?"+(p1==p2));
System.out.println("p1.equals(p2)?"+( p1.equals(p2) ));
}
}