[상속-17] toString()

seratpfk·2022년 8월 2일
0

JAVA

목록 보기
67/96

Object클래스의 toSting() 메소드

  • 클래스의 이름과 객체의 해시코드를 @로 연결한 문자열을 반환
  • 객체의 해시코드를 통해서 객체의 참조값을 확인 가능

toSting() 메소드를 사용하는 방법

Person클래스

	public String toString() {
		return "이름 : " + name;  // System.out.println(person);에서 사용됨
	}

Main클래스

		Person person = new Person();
		person.setName("james");
		System.out.println(person);  // 이름 : james

출력:
이름 : james

equals()

Main클래스

Person p1 = new Person();
Person p2 = new Person();
p1.setName("kim");
p2.setName("kim");
System.out.println(p1.equals(p2));
  • p1과 p2는 이름이 "kim"으로 동일
  • But, 서로 다른 객체이기 때문에 false가 반환됨

toSting() 오버라이드

  • 두 객체의 문자열이 동일하면 동일한 객체로 판단할 수 있도록 equals() 메소드를 오버라이드 함.

Person클래스

	@Override
	public boolean equals(Object anObject) {  // p1.equals(p2)에서 사용됨
		Person p = (Person) anObject;
		return name.equals(p.name);
	}

출력:
true

0개의 댓글