- Object 클래스는 모든 클래스들의 조상임
- 상속받지 않는 모든 클래스는 자동으로 Object 클래스를 상속받음 ( extends Object { } )
- Object 클래스에 다양한 메소드가 정의되어 있기 때문에, 어떤 클래스에서든지 다양한 메소드를 상속받아 사용할 수 있음
Calculator c1 = new Calculator();
System.out.println(c1); // Calculator@1dbd16a6
// Calculator 클래스가 toString이 정의되어 있는 Object 클래스를 상속받아서 자동으로, 암시적으로 toString()을 호출하기 때문에 System.out.println(c1.toString)과 같음
// "@" : 구분자 역할
// 1dbd16a6 : 인스턴스를 식별해주는 식별자 (즉, 인스턴스 주소)
- toString( ) : 객체를 문자화시키는 메소드
- toString( )을 오버라이딩해서 클래스에서 재정의할 수도 있음
public String toString() {
return super toString() + ", left: " + this.left + ", right: " + this.right;
// 기본적인 toString 출력과 재정의한 출력이 함께 출력됨
}
- equals( ) : 객체를 비교하는 메소드
Student s1 = new Student("handsukite");
Student s2 = new Student("roseline");
System.out.println(s1 == s2); // false
System.out.println(s1.equls(s2)); // false
// s1과 s2는 다른 메모리 값을 가지기 때문에 false가 반환됨
- 인스턴스 이름이 같을 때 equals( )의 결과로 true가 나오게 하려면, equals( )를 오버라이딩해서 클래스에서 재정의하면 됨
class Student {
String name;
Student(String name) {
this.name = name;
}
public boolean equals(Object obj) {
// equals는 오버라이딩하지 말고 그대로 쓰는 것이 권장됨
Student s = (Student)obj;
// 상위 클래스를 하위 클래스로 형변환할 때는 명시해줘야 함
// 하위 클래스를 상위 클래스로 형변환할 때는 다형성에 의해서 암시적 형변환이 가능함
return this.name == s.name;
}
}
class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student("handsukite");
Student s2 = new Student("roseline");
System.out.println(s1 == s2);
// 원시 데이터 형을 비교할 때는 비교 연산자(==)를 사용하는 것이 권장됨
System.out.println(s1.equals(s2));
// 문자열이나 객체를 비교할 때는 equals를 사용하는 것이 권장됨
}
}
- finalize( ) : 객체가 소멸될 때 호출되기로 약속된 메소드
- 객체가 소멸될 때 해야 될 작업이 있다면 finalize를 오버라이딩해서 재정의하면 됨
- "가비지 컬렉션 (Garbage Collection)" : 램을 사용하지 않는 데이터를 램에서 자동으로 제거하는 기능
- "clone" : 객체를 복제하는 기능
class Student implements Cloneable { ... }
// Cloneable 메소드는 비어있는 메소드이며, 클래스가 Cloneable 하다고 명시해 줄 뿐임
- 접근 제어자는 protected 임
- java.lang 패키지에 속해 있기 때문에 직접 clone 메소드를 호출할 수 없음
- 상위 클래스에 RuntimeException이 없기 때문에 throws를 사용해 예외를 전가해야 함
class Student implements Cloneable {
String name;
Studnet(String name) {
this.name = name;
}
public Object clone() throws CloneNotSupportedExpection {
return super.clone();
}
}
public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student("handsukite");
try {
Student s2 = (Student)s1.clone();
} catch (CloneNotSupportedExpection e) {
e.printStackTrace();
}
}
'onYouTube > Java' 카테고리의 다른 글
참조 (0) | 2021.03.27 |
---|---|
상수와 enum (0) | 2021.03.27 |
예외 (0) | 2021.03.26 |
다형성 (Polymorphism) (0) | 2021.03.24 |
인터페이스 (Interface) (0) | 2021.03.24 |