본문 바로가기
java

clone 메서드

by improve 2024. 1. 31.
package org.example;


import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
@AllArgsConstructor
public class Point {

    private int xpos;
    private int ypos;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }


    //    public Point(int xpos, int ypos) {
//        this.xpos = xpos;
//        this.ypos = ypos;
//    }
//
//    @Override
//    public String toString() {
//        return "Point{" +
//                "xpos=" + xpos +
//                ", ypos=" + ypos +
//                '}';
//    }
//
//    public void setXpos(int xpos) {
//        this.xpos = xpos;
//    }
//
//    public void setYpos(int ypos) {
//        this.ypos = ypos;
//    }
//
//    public int getXpos() {
//        return xpos;
//    }
//
//    public int getYpos() {
//        return ypos;
//    }
}

 

 

클론 메서드를 정의 해준다.

 

package org.example;

public class Main4 {

    public static void main(String[] args) {


        Point org = new Point(10, 20);
        Point clo = null;

        try {
            clo = (Point) org.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }


        System.out.println(org);
        System.out.println(clo);

        org.setXpos(20);
        System.out.println(org);
        System.out.println(clo);
    }
}

 

 

이렇게 하면 null값이 반환이 된다.

'java' 카테고리의 다른 글

컬렉션 2  (2) 2024.02.01
래퍼 클래스  (0) 2024.01.31
Object class  (1) 2024.01.31
JAVA 의 메모리 모델  (0) 2024.01.31
컬렉션  (0) 2024.01.30