자바에서 모든 클래스는 사실 Object를 암시적으로 상속받고 있는 것이다
Object는 모든 클래스의 조상이라고 할 수 있다
이유 : 모든 클래스가 공통으로 포함하고 있어야 하는 기능을 제공하기 위해서다.
object 메소드
toString
객체를 문자로 표현하는 메소드
ex 1 )
class Calculator{
int left, right;
public void setOprands(int left, int right){
this.left = left;
this.right = right;
}
public void sum(){
System.out.println(this.left+this.right);
}
public void avg(){
System.out.println((this.left+this.right)/2);
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setOprands(10, 20);
System.out.println(c1);
// 같은 의미
System.out.println(c1.toString());
}
}
Calculator의 인스턴스 c1을 화면에 출력
인스턴스에 대한 고유한 식별 값은 컴파일 할 때 마다 달라질 것이다.
ex 2 )
class Calculator{
int left, right;
public void setOprands(int left, int right){
this.left = left;
this.right = right;
}
public void sum(){
System.out.println(this.left+this.right);
}
public void avg(){
System.out.println((this.left+this.right)/2);
}
public String toString(){
return "left : " + this.left + ", right : "+ this.right;
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setOprands(10, 20);
System.out.println(c1);
System.out.println(c1.toString());
}
}
실행 결과
left : 10, right : 20
left : 10, right : 20
클래스 Calculator에 toString을 재정의(overiding)했다
toString 메소드는 자바에서 특별히 취급하는 메소드다.
equals
equals는 객체와 객체가 같은 것인지를 비교하는 API이다
ex 1)
class Student{
String name;
Student(String name){
this.name = name;
}
public boolean equals(Object obj) {
Student _obj = (Student)obj; // 타입으로 형 변환 (부모를 자식으로 바꾸는 것)
return name == _obj.name;
}
}
class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student("egoing");
Student s2 = new Student("egoing");
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //true
}
}
== 가 false인 이유
s1과 s2가 서로 다른 객체이기 때문
1. 객체 간에 동일성을 비교하고 싶을 때는 ==를 사용하지 말고 equals를 이용하자.
2. equals를 직접 구현해야 한다면 hashCode도 함께 구현해야 함을 알고 이에 대한 분명한 학습을 한 후에 구현하자.
3. equals를 직접 구현해야 한다면 eclipse와 같은 개발도구들은 equals와 hashCode를 자동으로 생성해주는 기능을 가지고 있다.
4. 이유가 분명하지 않다면 비교 연산자 == 은 원시 데이터형을 비교할 때만 사용하자.
finalize
객체가 소멸될 때 호출되기로 약속된 메소드
가비지 컬렉션(garbage collection)
객체가 소멸 되는 작업을 자동화한 것
ex)
어떤 인스턴스를 만들었고, 그것을 변수에 담았다. 그런데 그 변수를 사용하는 곳이 더 이상 없다면 이 변수와 변수에 담겨있는 인스턴스는 더 이상 메모리에 머물고 있을 필요가 없는 것이다. 자바는 이를 감지하고 자동으로 쓰지 않은 데이터를 삭제한다
clone
어떤 객체가 있을 때 그 객체와 똑같은 객체를 복제해주는 기능
class Student implements Cloneable{ // 복제를 하려면 Cloneable 인터페이스를 구현
// 사용 이유 : 클래스 Student가 복제 가능하다는 것을 표시하기 위해
String name;
Student(String name){
this.name = name;
}
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student("egoing");
try {
Student s2 = (Student)s1.clone(); // return 타입이 object 이므로 형변환
System.out.println(s1.name);
System.out.println(s2.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
실행 결과
egoing
egoing