1.Object클래스
- 모든 클래스의 최고 조상. 오직 11개의 메서드만을 가지고 있다.
- 자바 클래스가 아무것도 상속하지 않으면 java.lang 패키지의 Object 클래스를 자동으로 상속한다.
때문에 모든 자바클래스는 Object 클래스를 직접적 혹은 간접적으로 상속한다.
- 자바의 모든 인스턴스는 Object 클래스의 참조변수로 참조가능
- 자바의 모든 인스턴스를 대상으로 Object 클래스에 정의된 메소드 호출가능
<예> Object obj1 = new MyClass();
Object obj2 = new int[5]; //배열도 인스턴스이므로 가능
2.toString 메소드
- Object 클래스에는 toString 메소드가 다음의 형태로 정의되어 있다.
public String toString( ) { . . . .}
- 그리고 우리가 흔히 호출하는 println 메소드는 다음과 같이 정의되어 있다.
public void println(Object x) { . . . .}
- 때문에 모든 인스턴스는 println 메소드의 인자로 전달될 수 있다. 인자로 전달되면, toString 메소
드가 호출되고, 이 때 반환되는 문자열이 출력된다.
- 때문에toString 메소드는 적절한 문자열 정보를 반환하도록 오버라이딩 하는 것이 좋다.
3.equals 메소드
- ==(비교) 연산자는 참조값 비교를 한다. 따라서 JAVA에서는 인스턴스 간의 내용 비교를 목적으로
Object 클래스에 equals 메소드를 정의해 놓았다.
- 그러나 Object클래스에 정의된 equals()는 참조변수 값(객체의 주소)을 비교하여 같으면 true, 다르
면 false를 반환한다.
- 따라서 새로 정의되는 클래스의 내용 비교가 가능하도록 이 메소드를 오버라이딩하는 것이 좋다.
- String 클래스처럼 equals 메소드가 내용비교를 하는 경우도 많다.
예제 1.
package Quiz;
public class EncapsulationEquals {
public static void main(String[] args) {
Rectangle rec1= new Rectangle(1, 2, 8, 9);
Rectangle rec2= new Rectangle(2, 3, 5, 5);
Rectangle rec3= new Rectangle(1, 2, 8, 9);
if(rec1.equals(rec2))
System.out.println("rec1과 rec3의 내용 정보는 같다.");
else System.out.println("rec1과 rec2의 내용 정보는 다르다.");
}//main End
}//class End
class Point
{
private int xPos, yPos;
public Point(int x, int y)
{
xPos=x;
yPos=y;
}
public void showPosition()
{
System.out.printf("[%d, %d]", xPos, yPos);
}
@Override
public boolean equals(Object obj) {
if(xPos==((Point)obj).xPos && yPos==((Point)obj).yPos) { //Object에는 xPos,yPos가 없어서 눈높이를 낮춰서
return true; //Point를 강제 형변환 해줘야 xPos,yPos에 접근이 가능하다.
}else {
return false;
}
}
}
class Rectangle
{
private Point upperLeft, lowerRight;
public Rectangle(int x1, int y1, int x2, int y2)
{
upperLeft=new Point(x1, y1);
lowerRight=new Point(x2, y2);
}
public void showPosition()
{
System.out.println("직사각형 위치정보...");
System.out.print("좌 상단: ");
upperLeft.showPosition();
System.out.println("");
System.out.print("우 하단: ");
lowerRight.showPosition();
System.out.println("\n");
}
@Override
public boolean equals(Object obj) {
// int equal_x=((Rectangle)obj).upperLeft.xPos;
// int equal_y=((Rectangle)obj).upperLeft.yPos;
// int equal_x2=((Rectangle)obj).lowerRight.xPos;
// int equal_y2=((Rectangle)obj).lowerRight.yPos;
//
// if(this.upperLeft.xPos==equal_x && this.upperLeft.yPos==equal_y) {
// if(this.lowerRight.xPos==equal_x2 && this.lowerRight.yPos==equal_y2) {
// return true;
// }else {
// return false;
// }
// }else {
// return false;
// }
// }
Rectangle cmp=(Rectangle)obj;
if(this.upperLeft.equals(((Rectangle)obj).upperLeft) && this.lowerRight.equals(cmp.lowerRight)){
return true;
}else
return false;
}
}