자바(java) 질문 : clone 메소드 오버라이딩을 왜 해야하는지 누가 좀 자...
-
게시물 수정 , 삭제는 로그인 필요
clone 메소드를 오버라이딩 해야하는 이유에 대해서 공부중인데요.
소스파일 : InstanceCloning.java
class Point implements Cloneable
{
private int xPos;
private int yPos;
public Point(int x, int y)
{
xPos=x;
yPos=y;
}
public void showPosition()
{
System.out.printf("[%d, %d]", xPos, yPos);
System.out.println("");
}
// public Object clone() throws CloneNotSupportedException //16행
// {
// return super.clone();
// } //19행
}
class InstanceCloning
{
public static void main(String[] args)
{
Point org=new Point(3, 5);
Point cpy;
try
{
cpy=(Point)org.clone(); //31행
org.showPosition();
cpy.showPosition();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
16행~19행을 주석 처리하고 컴파일하면 다음과 같은 에러 메세지가 나타납니다.(주석처리하지 않으면 에러 없음)
InstanceCloning.java:31: error: clone() has protected access in Object
cpy=(Point)org.clone();
^
1 error
Point 클래스와 InstanceCloninig 클래스는 모두다 clone메소드가 정의된 Object 클래스를 간접상속하니까 오버라이딩 하지않아도 clone 메소드를 호출할 수 있는거 아닌가요? 왜 컴파일 에러가 나타나는지 이해가 안갑니다.
왜냐하면 아래 소스파일도 위와 비슷한 상황인데 컴파일 에러가 나타나지 않거던요.
소스파일 : Test.java
class Object
{
protected void showInfo()
{
System.out.println("Object");
}
}
class BBB extends Object
{
// protected void showInfo()
// {
// System.out.println("BBB");
// super.showInfo();
// }
}
class Test extends Object
{
public static void main(String[] args)
{
BBB instBBB=new BBB();
instBBB.showInfo();
}
}
제가 뭘 잘못알고 있는거 같은데 자세히 설명 좀 해주시면 정말 감사하겠습니다.
clone 메소드를 오버라이딩 해야하는 이유에 대해서 공부중인데요.
소스파일 : InstanceCloning.java
class Point implements Cloneable
{
private int xPos;
private int yPos;
public Point(int x, int y)
{
xPos=x;
yPos=y;
}
public void showPosition()
{
System.out.printf("[%d, %d]", xPos, yPos);
System.out.println("");
}
// public Object clone() throws CloneNotSupportedException //16행
// {
// return super.clone();
// } //19행
}
class InstanceCloning
{
public static void main(String[] args)
{
Point org=new Point(3, 5);
Point cpy;
try
{
cpy=(Point)org.clone(); //31행
org.showPosition();
cpy.showPosition();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
16행~19행을 주석 처리하고 컴파일하면 다음과 같은 에러 메세지가 나타납니다.(주석처리하지 않으면 에러 없음)
InstanceCloning.java:31: error: clone() has protected access in Object
cpy=(Point)org.clone();
^
1 error
Point 클래스와 InstanceCloninig 클래스는 모두다 clone메소드가 정의된 Object 클래스를 간접상속하니까 오버라이딩 하지않아도 clone 메소드를 호출할 수 있는거 아닌가요? 왜 컴파일 에러가 나타나는지 이해가 안갑니다.
왜냐하면 아래 소스파일도 위와 비슷한 상황인데 컴파일 에러가 나타나지 않거던요.
소스파일 : Test.java
class Object
{
protected void showInfo()
{
System.out.println("Object");
}
}
class BBB extends Object
{
// protected void showInfo()
// {
// System.out.println("BBB");
// super.showInfo();
// }
}
class Test extends Object
{
public static void main(String[] args)
{
BBB instBBB=new BBB();
instBBB.showInfo();
}
}
제가 뭘 잘못알고 있는거 같은데 자세히 설명 좀 해주시면 정말 감사하겠습니다.