JAVA

[Java.4-3] 자바의 주요 클래스 : Object 클래스

식빵민 2022. 4. 19. 01:56

Object 클래스

  • java.lang 패키지에 포함
  • 모든 클래스의 슈퍼클래스 : 모든 클래스에 강제 상속
    • 모든 객체가 공통으로 가지는 객체의 속성을 나타내는 메소드 보유
메소드  설명
boolean equals(Object obj) obj가 가리키는 객체와 현재 객체가 같으면 true 리턴 
Class getClass() 현 객체의 런타임 클래스를 리턴
int hashCode() 현 객체의 해시코드 값 리턴
string toString() 현 객체에 대한 문자열 표현을 리턴
void notify() 현 객체에 대해 대기하고 있는 하나의 스레드를 깨운다
void notifyAll() 현 객체에 대해 대기하고 있는 모든 스레드를 깨운다
void wait() 다른 쓰레드가 깨울 때 까지 현재 스레드를 대기하게 한다
class Point {
	private int x,y,z;
	public Point(int x, int y) {
    	this.x = x;
        this.y = y;
	}
}
public class UsingObjectClass {
	public static void print(Object obj) {
		System.out.println(obj.getClass().getName()); 
        //클래스 이름 : Sum
        //실행 되고있는 클래스를 리턴 하고 클래스의 이름을 리턴한다.
		System.out.println(obj.hashCode()); 
        //해시 코드 값 출력(10진수) : --------
		System.out.println(obj.toString()); 
        //객체를 문자열로 만들어 출력("객체이름@16진수 해시코드 값") : Point@-------
		System.out.println(obj); //obj를 obj.toString()으로 자동 변환
        //객체 출력("객체이름@16진수 해시코드 값") : Point@-------
	}
	public static void main(String [] args) {
		Point p = new Point(2,3);
		print(p);
	}
}

*obj.getClass()  == Sum 클래스, Sum.getName() == Sum 클래스의 이름("Sum")

**객체를 구분하는 정보 : 클래스 이름, 해시 코드 값


Object 클래스의 주요 메소드

 

String toString() : 객체를 문자열로 반환

  • 객체+문자열 -> 객체.toString + 문자열로 자동 변환

 

 

public String toString() {
	return getClass().getName() +"@" + Integer.toHexString(hashCode());
}//Integer.toHexString(hashCode()) : 해시코드를 16진수로 바꾸는 메소드
Point p = new Point(2,3);
System.out.println(p); //자동 변환 p = p.toString();
String s = p + "점"; //자동 변환 s = p.toString() + "점";
  • 개발자는 자신만의 toString 오버라이딩
class Point {
	private int x, y;
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
}
	public String toString() {
		return "점(" + x + "," + y + ")";//오버라이딩
	}
}
public class ToStringEx {
	public static void main(String [] args) {
		Point p = new Point(2,3);
		System.out.println(p.toString());
		System.out.println(p); // p는 p.toString()으로 자동 변환
		System.out.println(p + "점"); // p.toString() + "입니다"로 자동 변환
	}
}

boolean equals(Object obj)

  • == 연산자 :  두개의 레퍼런스 비교
  • boolean equals(Object obj) : 두개의 레퍼런스가 같은 내용인지 비교
  • public boolean equals(Object obj) {
        return (this == obj);
    }//실제 equals 함수 코드
  • class Point {
    	...
    	public boolean equals(Object p) {//오버라이딩
    		Point p = (Point)obj;
    		if(x == p.x && y == p.y)
    			return true;
    		else return false;
    	}
    }
    
    Point a = new Point(2,3);
    Point b = new Point(2,3);
    Point c = new Point(3,4);
    Piint d = a;
    
    return(a == b) // false
    return(a == d) // true
    return(a.equals(b)) // true
    return(a.equals(c)) // false