Tratscher
Tratscher

Reputation: 11

How to clone an object which is extended from an abstract class?

I think the call "super.clone()" doesn't go to the Cloneable class but to the abstract class..

public class Mainprogramm { 
  Test original = new Test();
 Test copy = original.getClone();
}

public class Test extends AbstractClass implements Cloneable{
  public Test getClone(){
  try
    {
        return (Test) super.clone();
    }
    catch(CloneNotSupportedException a)
    {   
        return this;
    }
  }
}

public class AbstractClass implements Cloneable{
  //no abstract clone-method...
}

Upvotes: 0

Views: 666

Answers (1)

GhostCat
GhostCat

Reputation: 140457

You are thinking wrong:

I think the call "super.clone()" doesn't go to the Cloneable class but to the abstract class.

The point is: Cloneable is just an interface. And its presence does something completely different; see the javadoc:

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

In other words: you better study the concepts you intend to use; instead of just putting down some code and wondering what it might be doing. See here for example.

In that sense: yes, super.clone() does "go" to the abstract base class; but: that is the only place where you actually can call clone() on.

Upvotes: 1

Related Questions