본문 바로가기

Programming/자바

생활코딩 자바 - Object 클래스

소개

 

  • 상속

class O {}

=> class O extends class Object{} 와 의미 동일

 

=> 자바에서 모든 클래스는 암시적으로 class Object 상속

=> 오브젝트 클래스는 모든 클래스가 기본적으로 포함해야할 기능 제공

 

https://docs.oracle.com/javase/7/docs/api/index.html 참고

 

 

toString

Object class 의 대표적 메소드

: 객체를 문자화

 

  • CalculatorDemo

public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator c1 = new Calculator();
        c1.setOprands(10, 0); 
        c1.divide();
        System.out.println(c1);
    }
}

 

//

org.opentutorials.javatutorials.exception.Calculator@5305068a    => 인스턴스의 주소

 

  •  

        System.out.println(c1.toString());

 

//

org.opentutorials.javatutorials.exception.Calculator@5305068a

 

 

=> println 사용 시 toString 메소드 명시돼있지 않아도 암시적으로 호출하기 때문에 두 결과는 같음

=> 암시적으로 상속하는 오브젝트 클래스 내에 toString 메소드가 있기에 발생하는 일

 

  • toString 구현체

* ctrl 키 누르면서 메소드 누르면 구체적인 구현체로 이동 가능

 

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

 

  • toString 메소드 재정의(오버라이딩)

public String toString() {
     return "left: "+ this.left+", right: "+this.right;
    }

 

~

 

 System.out.println(c1.toString());

 

//

left: 10, right: 0

 

 

 

equals

: 객체와 객체가 같은 것인지 비교

 

  •  

class Student{
String name;
Student(String name){
this.name = name;
}}

public class ObjectDemo {
public static void main(String[] args) {
Student s1 = new Student ("egoing");
Student s2 = new Student ("egoing");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}}

 

//

false

false

 

  •  

class Student{
String name;
Student(String name){
this.name = name;
}
public boolean equals(Object obj) {    => 2. s2 인자는 Object obj 매개변수로 들어와 equals 메소드에 유입됨

return true;
}
}

public class ObjectDemo {

public static void main(String[] args) {
Student s1 = new Student ("egoing");
Student s2 = new Student ("egoing");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));    => 1. equals 메소드는 s1 인스턴스에 소속돼있음 -> 인자로 s2 전달됨
}

}

 

 

=> Object obj = s2

=> Object 데이터타입인 obj에 그 하위클래스 데이터타입인 Student s2 대입하려고 함

=> 자식 데이터타입을 부모 데이터타입 갖는 변수에 할당

=> 다형성 관련/ 자식 데이터타입은 부모 데이터타입에 할당될 수 있음

 

s2를 obj에 대입할 시 String name에 접근 불가

=> Object 데이터타입에는 name 멤버 존재하지 않아서

=> Student 데이터타입에 다시 대입

 

  • Student 데이터타입에 대입

class Student{
String name;
Student(String name){
this.name = name;
}
public boolean equals(Object obj) {
Student s = obj;
return true;
}
}

 

//

Type mismatch: cannot convert from Object to Student

 

=> 부모는 자식의 데이터타입으로 할당 X

 

=> obj를 Student 클래스로 강제(명시적) 형변환시켜야 함

 

  • 명시적 형변환

class Student{
String name;
Student(String name){
this.name = name;
}
public boolean equals(Object obj) {
Student s = (Student) obj;
return this.name == s.name;
}
}

public class ObjectDemo {

public static void main(String[] args) {
Student s1 = new Student ("egoing"); 
Student s2 = new Student ("egoing");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}}

 

//

false
true

 

 

* hashcode 메소드도 함께 자주 사용됨

 

finalize

객체가 소멸할 때 호출되기로 약속된 메소드

전문가들 비추천

 

garbage collection

인스턴스는 내부 메모리(RAM) 사용

램은 가장 빠른 저장장치지만 비싸고 용량 작음 => 램 적게 사용하는 것이 좋은 프로그램 => 사용하지 않는 메모리 제거 방법 필요 => 자바에서는 해당 작업 자동화됨 (가비지 콜렉션)

 

 

clone

객체 복제

 

  •  

class Student1{    => JVM에 복제 가능한 클래스임을 알려야 함   => Cloneable 인터페이스 구현
String name;
Student1(String name){
this.name = name;
}}

public class Clone {

public static void main(String[] args) {
Student1 s1 = new Student1 ("egoing");
s1.clone();
}

}

 

  • Clonealbe 인터페이스로 JVM에 알리기

class Student1 implements Cloneable{    => Cloneable은 구분자 역할함
String name;
Student1(String name){
this.name = name;
}}

public class Clone {

public static void main(String[] args) {
Student1 s1 = new Student1 ("egoing");
s1.clone();=> 접근제어자 : protected Object   => 서로 다른 패키지에서 호출 X, 서로 다른 패키지더라도 상속은 가능
}}

 

  •  

class Human{
protected String test() {
return "test";
}
}

class Student1 extends Human implements Cloneable{    
String name;
Student1(String name){
this.name = name;
}}

public class Clone {

public static void main(String[] args) {
Student1 s1 = new Student1 ("egoing");
s1.test();
}}

 

=>Java.Lang.Object => 오브젝트 클래스는 클론과 다른 패키지에 있으므로 직접 구현 불가

 

  •  

class Student1 implements Cloneable{
String name;
Student1(String name){
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}}

public class Clone {

public static void main(String[] args) {
Student1 s1 = new Student1 ("egoing");
try {
Student1 s2 = (Student1) s1.clone();
System.out.println(s1.name);
System.out.println(s2.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

 

//

egoing
egoing

 

음 어렵다 마지막 clone은 완벽히는 이해 안돼서 한번더 들어야할듯..

 

 

 

 

 

 

 

 

 

 

 

 

 

'Programming > 자바' 카테고리의 다른 글

생활코딩 자바 - 참조 ?  (0) 2022.04.19
생활코딩 자바 - 상수2 - enum  (0) 2022.04.18
생활코딩 자바 - 예외  (0) 2022.04.12
생활코딩 자바 - 다형성  (0) 2022.04.08
생활코딩 자바 - 인터페이스  (0) 2022.04.08