Cloneable (identity, equality)

호모루덴스·2020년 3월 12일
0

java

목록 보기
1/1

package java.lang

Cloneable.java

public interface Cloneable {
}

A class implements the Cloneable interface to indicate to the {@link java.lang.Object#clone()} method that it is legal for that method to make a field-for-field copy of instances of that class.
By convention, classes that implement this interface should override
Object.clone (which is protected) with a public method.

Object.java

/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass.
*/
protected native Object clone() throws CloneNotSupportedException;

Example

public class Student implements Cloneable {

  private String grd; // 학년
  private String nm; //  이름

  @Override
  public Object clone() throws CloneNotSupportedException {
	return super.clone();
  }
  
}
public static void main(String[] args) throws CloneNotSupportedException {
        Student student = new Student();
        student.setGrd("1");
        student.setNm("홍길동");
        
        // 값이 같고 주소는 다른 새로운 객체를 만든다
        /* debug:: step into
         * Student의 clone() >> returns super.clone();
         */
        Student student2 = (Student) student.clone();
		
        // equality (true)
        if (student == student2) {
            System.out.println("== true");
        } else {
            System.out.println("== false");
        }
		
        // identity (false)
        if (student.equals(student2)) {
            System.out.println("equals true");
        } else {
            System.out.println("equals false");
        }

        System.out.println(student.hashCode()); //303563356
        System.out.println(student2.hashCode()); //135721597
        System.out.println(student.toString());
        System.out.println(student2.toString());
    }
profile
hola 공무원 때려친 코린이입니다

0개의 댓글