Scala: How can I implement a clone method on a superclass, and use it in a subclass?

java clone method
which method of object class can clone an object
remove this clone implementation use a copy constructor or copy factory instead
override clone method in java
java 8 clone object
java copy constructor
clone should not be overridden
why is clone method protected

I might be approaching this the wrong way, but I'd like to have an object like this:

class MyDataStructure {
  def myClone = {
    val clone = new MyDataStructure
    // do stuff to make clone the same as this

class MyDataStructureExtended(val foo: String) extends MyDataStructure


val data = MyDataStructureExtended
val dataClone = data.clone

So, the problem is that dataClone is of type MyDataStructure, not MyDataStructureExtended as I'd hoped.

I thought about adding a type T to the super class, that the subclass can specify (e.g. itself), but that didn't seem very promising.

Assuming you want to minimize amount of ceremony in the subclasses, here is my suggestion:

class A extends Cloneable {
  protected[this] def myCloneImpl[T] = {
    val justLikeMe = this.clone
    // copy values and such.
    // Note that the Object.clone method already made a shallow copy, but you may want
    // to deepen the copy or do other operations.
  def myClone = myCloneImpl[A]

class B extends A {
  override def myClone = myCloneImpl[B]

By extending java.lang.Cloneable and calling the Object.clone method, you ensure that your runtime type is the same as the object being cloned. The static type is coerced with a type-cast (asInstanceOf[T]). You will need to override the myClone method in each subclass and specify the type, but it should be a one-liner.

Java Cloning: Copy Constructors vs. Cloning, In order to implement cloning, we need to configure our classes and to follow cases from our clone() method, we call the clone() method of the superclass. We should use clone to copy arrays because that's generally the  Notice that if you change the type of the variable to id, the warning disappears -- the compiler can no longer reason about what methods are available. If it turns out that the object to which you send myString doesn't respond (i.e., if the object really is a Foo instead of a Bar , or one of Foo 's subclasses that doesn't implement myString

As you have suggested, abstract types, or generic parameters, are what you need. Do you require that MyDataStructure not be a trait or abstract class? The following defines MyDataStructure to be an abstract class, but you can make it a trait as well.

abstract class MyDataStructure {
  type T
  def myClone: T

class MyDataStructureExtended(foo: String) extends MyDataStructure {
  type T = MyDataStructureExtended
  def myClone = new MyDataStructureExtended(foo)

The results from the Scala interpreter show that the myClone method defined in MyDataStructureExtended is the correct type.

scala> val mde = new MyDataStructureExtended("foo")
val mde = new MyDataStructureExtended("foo")
mde: MyDataStructureExtended = MyDataStructureExtended@3ff5d699
scala> val cloned = mde.myClone
val cloned = mde.myClone
cloned: MyDataStructureExtended = MyDataStructureExtended@2e1ed620

You might want to restrict T so that its type can only be that of MyDataStructure subclasses

abstract class MyDataStructure {
  type T <: MyDataStructure
  def myClone: T

I don't know your requirements, but I believe that Scala 2.8 will have some nice functionality with case classes and named arguments that allow one to clone case classes with a copy method.

Scala for the Impatient, The example in the preceding section can enrage OO purists. Shouldn't price be a method of the superclass? Shouldn't each subclass override it? For example, the Scala List is implemented with case classes. Those automatically generated methods do what you think they do—print, compare, hash, and copy each field  Sometimes, we require just method declaration in super-classes. This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class.

Hard to say whether you're doing it right with such a vague problem description, but it's actually pretty straightforward to do this. You can simply override myclone in MyDataStructureExtended such that it returns the more specific type. When you have a variable of the more specific type, you'll be able to use the more specific clone method as well.

Example code in case that description was unclear:

class A {
  def getMe = this

class B extends A {
  override def getMe = this
  def isAnInstanceOfB = true

And a corresponding REPL session:

scala> val a = new A
a: A = A@1a6eeab

scala> val b = new B
b: B = B@a36771

scala> a.getMe
res0: A = A@1a6eeab

scala> a.getMe.isAnInstanceOfB
<console>:7: error: value isAnInstanceOfB is not a member of A

scala> b.isAnInstanceOfB      
res2: Boolean = true

scala> b.getMe.isAnInstanceOfB
res3: Boolean = true

Programming in Scala, If the member in the subclass is concrete and the member of the superclass is abstract, we also say that the concrete member implements the abstract one. For example, given an ArrayElement ae, you can query its width using ae.width, of a real project, you might consider returning a defensive copy of the array instead. The customary first step in any implementation of clone() is to invoke the superclass's implementation of clone(). If you are writing a clone() method for a direct subclass of class Object, you

I think this could be the solution. This is not inherited and you can do some modification to achieve your thing. Good Luck.

class CloneableClass extends scala.Cloneable {
   def myMethod: Unit = println("Inside "+this.getClass)
   override def clone(): CloneableClass =super.clone().asInstanceOf[this.type]

class CloneableDemo  {
  val cc = new CloneableClass
  val cc1 = cc.clone()

object CloneObject extends App {
  val cd = new CloneableDemo

Java: Classes that override "clone" should be "Cloneable" and call , Java 8's "Files.exists" should not be used Overriding clone() without implementing Cloneable can be useful if you want to control how subclasses clone themselves, but otherwise, it's probably a mistake. class BaseClass implements Cloneable { @Override public Object clone() throws CloneNotSupportedException  It's still only in the superclass. But that code can be accessed through the subclass and can be used by the subclass. Example: methodA() is a method in Sup. Sub extends Sup, so now methodA() can be accessed through Sub like so: subInstance.methodA(). But that will actually invoke methodA() in the superclass.

Classes & Objects, By contrast, the superclass constructor sc normally refers to a class which is not a by the superclass constructor sc must be a subclass of the superclasses of all If a formal parameter is given, it can be used as an alias for the reference this trait can override the hook by re-implementing the delayedInit method, which is  Private members of the superclass cannot be accessed by the subclass, so technically speaking they are not inherited. True When an instance of the subclass is created, the non-private methods of the superclass are available through the subclass object.

OBJ07-J. Sensitive classes must not let themselves be , Java's object cloning mechanism allows an attacker to manufacture new defines class SensitiveClass , which contains a character array used to hold a file name, subclasses the nonfinal SensitiveClass and provides a public clone() method: Sensitive classes that extend from a superclass that implements Cloneable  How to force call superclass implementation Object.toString() rather than subclass overriding implementation on an object in Java. java,override,superclass,subclassing. You need to use System.identityHashCode() to get the actual (original) hash code.

Cloning, Collections, and Inner Classes: Chapter 8 of Objects and , How to clone objects, put objects into collections, and create nested top level classes, The clone() method, a member of class Object , is Java's mechanism for one of its superclasses other than Object , must implement the Cloneable interface. If all you do is implement Cloneable , only subclasses and members of the  Accessing Superclass Members. If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.You can also use super to refer to a hidden field (although hiding fields is discouraged).