Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter03 : Object_clone 본문

JAVA/chapter20_api

chapter03 : Object_clone

GAWON 2023. 5. 30. 18:18
package org.joonzis.ex;
// 반드시 Cloneable 인터페이스를 구현하자
// 복제 가능한 Person 클래스로 만들기 위함
class Person implements Cloneable{
	private String name;
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "이름 : " + name + ", 나이 : " + age;
	}
	@Override
	public Object clone() {	// protected -> public으로 변경
		// Object obj = super.clone();  해도 되지만
		// 그러면 try-catch이후 return 값을 넣지 못함
		Object obj = null; 
		try {
			obj = super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
public class Ex03_Object_clone {
	public static void main(String[] args) {
		
		Person per1 = new Person("김씨", 12);
		System.out.println(per1);
		
		Person clonePer = (Person)per1.clone();
		System.out.println(clonePer);
		
		
	}
}

'JAVA > chapter20_api' 카테고리의 다른 글

chapter06 : StringBuffer  (0) 2023.05.30
chapter05 : String  (0) 2023.05.30
chapter04 : System  (0) 2023.05.30
chapter02 : Object_equals  (0) 2023.05.30
chapter01 : Object  (0) 2023.05.30