Object
java의 lang패키지는 가장 기본적인 클래스들이 모여있는 패키지이다.
컴파일시 자동으로 import java.lang.*;문장이 추가된다. 따라서 import문을 쓰지 않더라도 자동으로 사용이 가능하다.
다양한 자바의 기본 클래스와 인터페이스가 속해져 있다.
포함된 여러 클래스들을 알아보자.
모든 클래스의 최상위 클래스이다. 모든 클래스는 자동으로 Object클래스를 상속받는다.
👉 따라서 모든 클래스는 Object의 메소드를 사용할 수 있고, Object 메소드의 재정의가 가능하며, Object형으로 변환이 가능하다.
final예약어로 선언한 메서드는 재정의할 수 없다.//1. 모든 클래스는 Object를 상속받는다. (자동 컴파일)
class 클래스명 extends Object { //extends Object문을 자동으로 포함한다.
//2. 모든 클래스는 Object로 형변환이 가능하다.
Object ac = new AccessControl3();
//3. 클래스 내에서 Object의 메소드를 사용할 수 있다.
String s = ac.toString();
//4. 클래스내에서 Object의 메소드를 재정의할 수 있다.
public class AccessControl3 {
@Override
public String toString() { //object의 toString메소드를 재정의
return super.toString();
}
| 메소드 | 설명 |
|---|---|
String toString() | 현재 객체의 문자열을 반환 |
protected Object clone() | 객체 자신의 복사본 반환 (깊은 복사) |
boolean equals(Object obj) | 두 개의 객체가 같은지 비교하여 같으면 true를, 같지 않으면 false를 반환 |
protected void finalize() | 가비지 컬렉션 직전에 객체의 리소스를 정리할 때 호출 |
Class getClass() | 객체의 클래스형을 반환 |
int hashCode() | 찾을 값을 입력하면 저장된 위치를 알려주는 해시코드를 반환 |
void notify() | wait된 스레드 실행을 재개할 때 호출 |
void notifyAll() | wait된 모든 스레드 실행을 재개할 때 호출 |
void wait() | 스레드를 일시적으로 중지할 때 호출 |
void wait(long timeout) | 주어진 시간만큼 스레드를 일시적으로 중지할 때 호출 |
void wait(long timeout, int nanos) | 주어진 시간만큼 스레드를 일시적으로 중지할 때 호출 |
//클래스 이름 @ 코드값
getClass().getName() + '@' + Integer.toHexString(hashCode())
⚠️ 컴파일러는 객체만 출력시 자동으로
toString을 붙여준다.
🤔System.out.println(문자열);시 해시코드가 아닌 문자열이 정상 출력된다. String객체에toString()이 재정의되었기 때문이다.
String클래스: 문자열 자체를 출력한다.
Integer클래스: 숫자 자체를 출력한다.
File클래스: 경로값을 리턴한다.
잘 구현된 toString이란 객체가 가진 주요정보를 모두 반환하는 것이며, 스스로를 완벽히 설명하는 문자열이어야한다.
class마다 자신의 주요정보를 잘 설명할 수 있는 toString()메소드를 재정의하는 것이 좋다.
✍️ 예시코드
class Student {
String studentName;
int studentID;
boolean scholarship;
Student(String studentName,int studentID,boolean scholarship){
this.studentName = studentName;
this.studentID = studentID;
this.scholarship = scholarship;
}
//toString() 재정의
@Override
public String toString() {
return "student의 정보 {" +
"studentName='" + studentName + '\'' +
", studentID=" + studentID +
", scholarship=" + scholarship +
'}';
}
}
public class Test0805 {
public static void main(String[] args) {
Student younghee = new Student("영희", 202045801, true);
Student minsu = new Student("민수", 202045802, false);
System.out.println(younghee); //student의 정보 {studentName='영희', studentID=202045801, scholarship=true}
System.out.println(minsu); //student의 정보 {studentName='민수', studentID=202045802, scholarship=false}
}
}
👉 실행화면
student의 정보 {studentName='영희', studentID=202045801, scholarship=true}
student의 정보 {studentName='민수', studentID=202045802, scholarship=false}
Student@7b23ec81
Student@6acbcfc0
💡 좋은 toString()의 활용
디버깅을 위해서 사용한다.
어떤 문제가 발생한 클래스가toString()이 잘 구현된 클래스일 경우 스스로를 완벽히 설명하는 문자열이 로깅될 것이고 그렇지 않을 때 보다 훨씬 더 원인을 발견하기 쉬워질 것이다.
사용자를 위한 메소드는 별도로 정의하는 것이 좋다.
String클래스 : 객체의 주소값이 아닌 실제 값을 비교해서 retrun한다.
문자열생성 방법에 따라==의 값이 달라진다.
new생성자 이용방법은 새로운 저장소를 가지기 때문이다.
그러나 String 클래스에서 재정의된 equals은 실제 값을 비교해 판단한다.
✍️ 예시코드
String str = "안녕";
String str_new = new String("안녕");
if(str == str_new){ //false
System.out.println("str == str_new 결과 : true");
}else{
System.out.println("str == str_new 결과 : false");
}
if(str.equals(str_new)){ //true
System.out.println("str.equals(str_new) 결과 : true");
}else{
System.out.println("str.equals(str_new) 결과 : false");
}
👉 실행화면
str == str_new 결과 : false
str.equals(str_new) 결과 : true
✍️예시코드
class Student {
String studentName;
int studentID;
boolean scholarship;
Student(String studentName,int studentID,boolean scholarship){
this.studentName = studentName;
this.studentID = studentID;
this.scholarship = scholarship;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student){
Student std =(Student) obj;
if(this.studentID == std.studentID){
return true;
}else {
return false;
}
}
return false;
}
}
public class Test0805 {
public static void main(String[] args) {
Student younghee = new Student("영희", 202045801, true);
Student younghee_1 = new Student("영희", 202045801, true);
System.out.println(younghee.equals(younghee_1)); //true
}
}
👉실행화면
true
오버라이딩 전
false
➕ 객체가 할당되지 않았을 때
null.eqauls(객체) - 오류가 발생한다.
생성된객체.eqauls(null) - 오류가 발생하지 않는다.
따라서 null값이 들어올만한 변수에는 eqaul을 쓰지 않는 것이 좋고, 가능성이 있는 변수라면 두번째의 방법으로 쓰는 것이 안전하다.
Student seohyun;
if(seohyun.equals(younghee)){
System.out.println("true");
}else {
System.out.println("false");
}
//java: variable seohyun might not have been initialized