Language/Java

6.1 java.lang 패키지 (object 클래스)

리져니 2021. 7. 15. 18:43

java.lang 패키지

자바 프로그래밍에 가장 기본이 되는 클래스들을 포함하고 있다.

* 때문에 import 없이 사용할수 있음

 

Object 클래스

1. equals(Object obj)

매개변수로 객체의 참조변수를 받아서 인스턴스와 비교한 결과값을 boolean값으로 알려준다

* equals 메서드는 주소값으로 비교를 하기 때문에, 두 Value인스턴스의 멤버변수 value의 값이 서로 같더라도 equals로 비교한 결과값은 false가 된다.

결국 두 개의 참조변수가 같은 객체를 참조하고 있는지(두 참조변수의 주소값이 같은지) 판단하는 기능을 함

public class Main {
    public static void main(String[] args) throws IOException {
        Value v1 = new Value(10);
        Value v2 = new Value(10);

        if (v1.equals(v2))
            System.out.println("same");
        else
            System.out.println("different");

        v2 = v1;
        if (v1.equals(v2))
            System.out.println("same");
        else
            System.out.println("different");
    }
}

class Value{
    int v;

    Value(int v){
        this.v = v;
    }
}

출력 결과: 

different
same

 

2. hashCode()

찾고자하는 값을 입력하면 그 값이 저장된 위치를 알려준다.

객체의 주소값으로 해시 코드를 반환하기 때문에 같은 생성자로 인스턴스를 만들더라도 출력되는 위치값이 다르다.

단, String 클래스는 문자열의 내용이 같으면 동일한 해시코드를 반환하도록 hashCode()가 오버라이딩 되어있다.

* System.identityHashCode(Object x)는 모든 객체에 대해 항상 다른 해시코드값을 반환한다.

public class Main {
    public static void main(String[] args) throws IOException {
        Card origin = new Card("heart",5);
        Card origin2 = new Card("heart",5);    
        
        System.out.println(origin.hashCode());
        System.out.println(origin2.hashCode());
        
        
        String str1 = new String("abc");
        String str2 = new String("abc");

        System.out.println(str1.hashCode());
        System.out.println(str2.hashCode());      
        
        System.out.println(System.identityHashCode(str1));
        System.out.println(System.identityHashCode(str2));
    }
}

결과:

 

 

3. toString()

인스턴스에 대한 정보를 문자열로 제공한다

public class Main {
    public static void main(String[] args) throws IOException {
        Card c1 = new Card();
        Card c2 = new Card();

        System.out.println(c1.toString());
        System.out.println(c2.toString());
    }
}

class Card{
    String kind;
    int num;

    Card(){
        this("SPADE", 1);
    }
}

결과:

클래스 이름과 해시코드가 출력된다.

만약 위와 같은 형태가 아닌 다른 형태로 출력문을 지정하고 싶다면, 오버라이딩을 통해 toString메서드를 작성해 주면된다. (++ toString을 오버라이딩 해놓으면 '인스턴스.toString()'대신 'System.out.println(인스턴스 변수)'를 써도 해당 메서드의 결과가 출력된다)

 

4. clone()

자신을 복제하여 새로운 인스턴스를 생성한다

얕은 복사와 깊은 복사

얕은 복사(shallow copy)

단순히 객체에 저장된 값을 복제할 뿐, 객체가 참조하고 있는 객체까지 복제하지 않음. 

(int, float 같은 단순값의 경우, 주소값을 복사하여 같은 인스턴스를 가리키게됨)

얕은 복사에서는 원본을 변경하면 복사본도 영향을 받는다.

 

깊은 복사(deep copy)

원본이 참조하고 있는 객체까지 복제 함.

(ArrayList 같은 참조 타입의 경우, 주소값이 아닌 새로운 메모리 공간에 값을 복사하여 각각의 인스턴스를 가리키게됨)

원본과 복사본이 서로 다른 객체를 참조하기 때문에 원본의 변경이 복사본에 영향을 미치지 않는다.

 

데이터 타입의 종류

* clone()을 사용하려면 복제할 클래스가 Cloneable인터페이스를 구현해야 한다

public class Main {
    public static void main(String[] args) throws IOException {

        Circle c1 = new Circle(new Point (1,1), 2.0);
        Circle c2 = c1.shallowCopy();
        Circle c3 = c1.deepCopy();

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);

        c1.p.x = 9;
        c1.p.y = 9;      
        c1.r = 3.0;

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);

    }
}

class Point{
    int x, y;

    Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    public String toString(){
        return  "x = " + x + ", y = " + y;
    }
}

class Circle implements Cloneable{
    Point p;
    double r;

    Circle(Point p, double r){
        this.p = p;
        this.r = r;
    }

    public Circle shallowCopy(){
        Object obj = null;
        try{
            obj = super.clone();
        }catch (CloneNotSupportedException e){}
        return (Circle) obj;
    }

    public Circle deepCopy(){
        Object obj = null;
        try{
            obj = super.clone();
        }catch (CloneNotSupportedException e){}

        Circle c = (Circle) obj;
        c.p = new Point(this.p.x, this.p.y);

        return c;
    }

    public String toString(){
        return "p = " + p + ", r = " + r;
    }
}

* super.colone() 사용이유: 조상의 clone() 메소드를 호출하기 위해서임. 만약 단순히 clone()이라고 적으면 자기 자신을 호출하는 재귀호출이 일어남

shallowCopy()의 경우에는 Object클래스의 clone()을 호출하기만함.

deepCopy()의 경우에엉 복제된 객체가 새로운 Point 인스턴스를 참조하도록 소스코드를 추가함.

 

결과

 

 

5. getClass()

자신이 속한 클래스의 Class객체(이름이 Class인 클래스의 객체)를 반환하는 매서드

Class 객체는 클래스의 모든 정보를 담고 있으며, 클래스 당 1개만 존재함. 클래스 파일이 클래스 로더에 의해 메모리에 올라갈때 자동으로 생성됨.

Class cObj = new Card().getClass();	//생성된 객체로 부터 얻음
Class cObj = Card.class;			// 클래스 리터럴(*.class)로 부터 얻음
Class cObj = Class.forName("Card");	// 클래스 이름으로부터 얻음

Systme.out.println(cObj.getName());	// Card
Systme.out.println(cObj.toGenericString());	// final class Card
Systme.out.println(cObj.toString);	// class Card

 

728x90

'Language > Java' 카테고리의 다른 글

7. 날짜, 시간 & 형식화  (0) 2021.07.19
6.2 java.lang패키지 (String 클래스)  (0) 2021.07.15
5. 예외처리  (0) 2021.07.14
4.7 객체 지향 프로그래밍 (인터페이스)  (0) 2021.07.12
4.6 객체 지향 프로그래밍 (다형성)  (0) 2021.07.09