Programming/Java
Clone() 과 공변의 룰
SharingWorld
2018. 4. 9. 15:31
class User {
private String name; // 인스턴스 필드
private int age;
private static int a; // 정적 필드(클래스 필드)
// class Printer {
static class Printer {
void print(User user) {
System.out.println("User.Printer.print()");
System.out.println(user.name);
}
}
void print() {
Printer printer = new Printer();
printer.print(this);
}
}
// interface - Cloneable
// => mark up interface
class Point implements Cloneable {
int x;
int y;
Point point;
// 공변의 룰
// : 부모 메소드의 반환 타입을 자식 타입으로 변환하는 것이
// 가능하다.
@Override
public Point clone() {
try {
// primitive type
Point copy = (Point) super.clone();
// reference type
if (point != null) {
copy.point = this.point.clone();
}
return copy;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void print() {
System.out.printf("Point(%d,%d)\n", x, y);
}
}
// 자바에서 깊은 복사를 수행하는 방법
// 1. Object
// : 모든 객체의 부모 클래스
// => 객체가 가져야 하는 기능
// 2. Object.clone 오버라이딩
// 3. protected -> public
// 4. 예외를 내부에서 처리한다.
// 5. 반환 타입을 변환한다.
class Rect {
private Point point;
public Rect(Point point) {
this.point = point.clone();
}
public void print() {
point.print();
}
}
public class Program_0302 {
public static void main(String[] args) {
Point p1 = new Point(10, 20);
Rect rect = new Rect(p1);
p1.y = 100;
rect.print();
}
// public static void main(String[] args) {
// // User user = new User();
// // User.Printer printer = new User.Printer();
//
// // User.Printer printer = new User.Printer();
//
// User user = new User();
// User user2 = user;
// }
}