Object와 오버라이딩, Wrapper 클래스

이상민·2023년 9월 6일
0

Java 기초문법

목록 보기
6/7

📘오버라이딩 하지 않은 메서드 사용시(Object 메서드 사용)

public class Student {
    String name;
    String number;
    int birthYear;

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "홍길동";
        s1.number = "1234";
        s1.birthYear = 1995;

        Student s2 = new Student();
        s2.name = "홍길동";
        s2.number = "1234";
        s2.birthYear = 1995;

        if(s1.equals(s2))
            System.out.println("s1==s2");
        else
            System.out.println("s1 != s2");

        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s1);

    }
}

결과

s1 != s2
1915910607
284720968
Student@170861

s1과 s2는 같은 값을 가지고 있는데도 불구하고, 다른 결과와, 해시코드 값을 출력한다.
이유는 equals, hashCode 메서드가 Object 클래스의 메소드를 사용하고 있기 때문이다.
또한 s1의 속성값이 출력되지 않고 객체의 주소값을 출력하고 있다.

📗equals()메서드와 hashCode()메서드 오버라이딩

  • equals() 메서드 오버라이딩시에 어떤 속성이 같아야 같다고 할 것인지 정할 수 있다.

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(number, student.number);
    }

number만 같다면 같다고 나오도록 오버라이딩 하였다.

결과

s1==s2
1509473
1509473

equals()메서드와 hashCode()메서드가 오버라이딩 되어 원하는 결과를 출력하였다.

📗toString()

  • toString()도 StringBuilder를 통해 원하는 형태로 오버라이딩 한다.
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Student{");
        sb.append("name='").append(name).append('\'');
        sb.append(", number='").append(number).append('\'');
        sb.append(", birthYear=").append(birthYear);
        sb.append('}');
        return sb.toString();
    }

결과

Student{name='홍길동', number='1234', birthYear=1995}

오버라이딩 한대로 출력된다.

📘Wrapper 클래스

오토 박싱

Integer i3 = 5;//Integer i3 = new Integer(5);

기본형 타입의 int가 자동으로 객체타입의 Integer로 변환되는것을 뜻함

오토 언박싱

int i4 = i3; // int i4 = i3.intValue();

반대로 객체타입의 Integer가 기본형 타입의 int로 변환되는것을 뜻한다.

profile
개린이

0개의 댓글