Polymorphic copy: Difference between revisions
Content deleted Content added
→{{header|Perl 6}}: add entry |
PascalABC.NET |
||
(53 intermediate revisions by 30 users not shown) | |||
Line 1:
{{task|Object oriented}}
An object is [[polymorphism|polymorphic]] when its specific type may vary.
The types a specific value may take, is called ''class''.
It is trivial to copy an object if its type is known:
<
int y = x;</
Here x is not polymorphic, so y is declared of same type (''int'') as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until [[run time]].
The objective is to create an exact copy of such polymorphic object (not to create a [[reference]], nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
=={{header|Ada}}==
<
procedure Test_Polymorphic_Copy is
package Base is
type T is tagged null record;
type T_ptr is access all T'Class;
function Name (X : T) return String;
end Base;
use Base;
package body Base is
function Name (X : T) return String is
Line 24 ⟶ 33:
end Name;
end Base;
-- The procedure knows nothing about S
procedure Copier (X : T'Class) is
Line 32 ⟶ 41:
end Copier;
-- The function knows nothing about S and creates a copy on the heap
function Clone (X : T'Class) return T_ptr is
begin
return new T'Class'(X);
end Clone;
package Derived is
type S is new T with null record;
overriding function Name (X : S) return String;
end Derived;
use Derived;
package body Derived is
function Name (X : S) return String is
begin
Line 47 ⟶ 62:
Object_1 : T;
Object_2 : S;
Object_3 : T_ptr := Clone(Object_1);
Object_4 : T_ptr := Clone(Object_2);
begin
Copier (Object_1);
Copier (Object_2);
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;
</syntaxhighlight>
The procedure Copier does not know the specific type of its argument.
Nevertheless, it creates an object Duplicate of exactly the same type. The function Clone makes a copy in the heap with the correct type and returns a pointer to it.
{{out}}
<pre>
Copied T
Copied S
Cloned T
Cloned S
</pre>
=={{header|Aikido}}==
Aikido has a native <code>clone</code> function that creates a (deep or shallow) clone of any variable of any type.
<
class T {
public function print {
Line 83 ⟶ 108:
scopy.print()
</syntaxhighlight>
{{out}}
before copy
class T
Line 92 ⟶ 116:
class T
class S
=={{header|ALGOL 68}}==
Whilst not having classes, inheritence and overloading as such, Algol 68 has structures which can contain members
that are procedures. The following shows how the task can be accomplished by using structre instances with
different values of the procedures.
<syntaxhighlight lang="algol68">BEGIN
# Algol 68 doesn't have classes and inheritence as such, however structures #
# can contain procedures and different instances of a structure can have #
# different versons of the procedure #
# this allows us to simulate inheritence by creating structure instances #
# with different procedures #
# the following declares a type (MODE) HORSE with two constructors, one for #
# a standard horse and one for a zebra (the "derived class"). #
# The standard horse has its print procedure set to thw print horse #
# procedure (the "base class" method). zebras get the print zebra procedure #
# (the "derived class" method). A convenience operator (PRINT) is defined #
# to simplify calling the horse/zebra print method of its horse parameter #
# = this PRINT operator is independent of which actual print method the #
# horse has - it just saved typeing "( print OF h )( h )" everywhere we #
# need to call the print method (euivalent to h.print(h) in e.g. C, Java, #
# etc.) #
# "class" #
MODE HORSE = STRUCT( STRING name, PROC(HORSE)VOID print );
# constructors #
PROC new horse = ( STRING name )HORSE: ( name, print horse );
PROC new zebra = ( STRING name )HORSE: ( name, print zebra );
# print methods: one for a standard horse and one for a zebra #
PROC print horse = ( HORSE h )VOID: print( ( "horse: ", name OF h ) );
PROC print zebra = ( HORSE h )VOID: print( ( "zebra: ", name OF h ) );
# print operator #
OP PRINT = ( HORSE h )VOID: ( print OF h )( h );
# declare and construct some horses and zebras #
HORSE h1 := new horse( "silver blaze" );
HORSE z1 := new zebra( "stripy" );
HORSE z2 := new zebra( "second zebra" );
# show their values #
PRINT h1; print( ( newline ) );
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) );
print( ( "----", newline ) );
# change the second zebra to be a copy of the first zebra #
z2 := z1;
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) );
print( ( "----", newline ) );
# change the name of the first zebra leaving z2 unchanged #
name OF z1 := "ed";
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) )
END</syntaxhighlight>
{{out}}
<pre>
horse: silver blaze
zebra: stripy
zebra: second zebra
----
zebra: stripy
zebra: stripy
----
zebra: ed
zebra: stripy
</pre>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
REM Create parent class T:
Line 122 ⟶ 214:
result% = FN(mycopy.retval)(RunTimeSize%)
PRINT result%
END</
{{out}}
<pre>
15129
Line 129 ⟶ 221:
=={{header|C}}==
Since C doesn't support classes, this is not quite so trivial.
Normally the code below would be split into a number of files.
Specificially there would be a header (.h) file and a source (.c) file for each of - BaseObj, Dog, and Ferret.
The code in "main" would also be a separate source file which would include Dog.h and Ferret.h header files (which would thems elves include the BaseObj.h header file.)
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 336 ⟶ 427:
ObjDestroy(o1);
return 0;
}</
=={{header|C sharp|C#}}==
<
class T
Line 377 ⟶ 468:
Console.WriteLine(clone.Name());
}
}</
{{out}}
<syntaxhighlight lang="text">S
S</
=={{header|C++}}==
<
class T
Line 432 ⟶ 523:
X copy = original; // copy it,
copy.identify_member(); // and check what type of member it contains
}</
=={{header|Common Lisp}}==
Line 438 ⟶ 529:
With structures, <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_cp_stu.htm copy-structure]</code> performs the right kind of copy. The object and its copy are compared under <code>eq</code>, <code>eql</code>, <code>equal</code>, and <code>equalp</code> to demonstrate that "The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to)."
<
(defstruct (sub (:include super)) bar)
Line 449 ⟶ 540:
(defmethod frob ((sub sub))
(format t "~&Sub has foo = ~w, bar = ~w."
(sub-foo sub) (sub-bar sub)))</
<pre>> (let* ((sub1 (make-sub :foo 'foo :bar 'bar))
Line 467 ⟶ 558:
The same technique works for <code>[http://www.lispworks.com/documentation/HyperSpec/Body/t_seq.htm sequence]</code> and its subclasses (e.g., <code>[http://www.lispworks.com/documentation/HyperSpec/Body/t_string.htm string]</code>, <code>[http://www.lispworks.com/documentation/HyperSpec/Body/t_seq.htm list]</code>) when <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_cp_seq.htm copy-seq]</code> is used rather than <code>copy-structure</code>.
<
(format t "~&sequence has ~w elements" (length sequence)))
(defmethod frob ((string string))
(format t "~&the string has ~w elements" (length string)))</
<pre>> (let* ((hw1 "hello world")
Line 488 ⟶ 579:
If we assume there are no data members, this will be quite short and simple:
<
override string toString() { return "I'm the instance of T"; }
T duplicate() { return new T; }
Line 506 ⟶ 597:
writeln(orig);
writeln(copy);
}</
{{out}}
<pre>I'm the instance of S
Line 513 ⟶ 604:
However this doesn't happen often in reality. If we want to copy data fields we should have something like copy constructor, that will
do the deep copy.
<
this(T t = null) {} // Constructor that will be used for copying.
Line 535 ⟶ 626:
override string toString() {
return "I'm the instance of S p: " ~
}
Line 556 ⟶ 647:
orig.custom('Y');
}</
{{out}}
<pre>I'm the instance of S p: Y23
I'm the instance of S p: X23</pre>
=={{header|Delphi}}==
{{trans|C#}}
<syntaxhighlight lang="delphi">program PolymorphicCopy;
type
T = class
function Name:String; virtual;
function Clone:T; virtual;
end;
S = class(T)
function Name:String; override;
function Clone:T; override;
end;
function T.Name :String; begin Exit('T') end;
function T.Clone:T; begin Exit(T.Create)end;
function S.Name :String; begin Exit('S') end;
function S.Clone:T; begin Exit(S.Create)end;
procedure Main;
var
Original, Clone :T;
begin
Original := S.Create;
Clone := Original.Clone;
WriteLn(Original.Name);
WriteLn(Clone.Name);
end;
begin
Main;
end.</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">S
S</syntaxhighlight>
=={{header|E}}==
Line 567 ⟶ 697:
In E, a generic copy for all objects can be built out of the serialization facility, by connecting an object recognizer to an object builder without even using any intermediate serialized form:
<
def copy(object) {
return deSubgraphKit.recognize(object, deSubgraphKit.makeBuilder())
}</
Since E does not have any static dispatch, this cannot be non-polymorphic without also being non-generic.
Line 577 ⟶ 707:
An example showing that it does indeed make copies follows. (For the task description, let <var>S</var> be the type of all serializable E objects, <var>T</var> be the <code>[http://wiki.erights.org/wiki/FlexList FlexList]</code> type (result of <code>diverge</code>), and the overriden method be <code> [http://wiki.erights.org/wiki/FlexList#push/1 push]</code>.
<
# value: [1].diverge()
Line 588 ⟶ 718:
? b
# value: [1, 2].diverge()</
See also: [[Deepcopy#E]]
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'types)
(lib 'struct)
(struct T (integer:x)) ;; super class
(struct S T (integer:y)) ;; sub class
(struct K (T:box)) ;; container class, box must be of type T, or derived
(define k-source (K (S 33 42)))
(define k-copy (copy k-source))
k-source
→ #<K> (#<S> (33 42)) ;; new container, with a S in box
k-copy
→ #<K> (#<S> (33 42)) ;; copied S type
(set-S-y! (K-box k-source) 666) ;; modify k-source.box.y
k-source
→ #<K> (#<S> (33 666)) ;; modified
k-copy
→ #<K> (#<S> (33 42)) ;; unmodified
(K "string-inside") ;; trying to put a string in the container box
😡 error: T : type-check failure : string-inside → 'K:box'
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<syntaxhighlight lang="elena">import extensions;
class T
{
Name = "T";
T clone() = new T();
}
class S : T
{
Name = "S";
T clone() = new S();
}
public program()
{
T original := new S();
T clone := original.clone();
console.printLine(original.Name);
console.printLine(clone.Name)
}</syntaxhighlight>
{{out}}
<pre>
S
S
</pre>
=={{header|F_Sharp|F#}}==
.NET objects have a protected method <code>MemberwiseClone</code>. This method creates a shallow copy of an object. Value type members are copied, i.e. not shared between clones. Reference type members, on the other hand, will reference the same objects after cloning.
<
// expose protected MemberwiseClone method (and downcast the result)
member x.Clone() = x.MemberwiseClone() :?> T
Line 608 ⟶ 798:
let s = new S()
let s2 = s.Clone() // the static type of s2 is T, but it "points" to an S
s2.Print() // prints "I'm an S!"</
=={{header|Factor}}==
shallow copy is achieved with the "clone" word.
Line 614 ⟶ 805:
Pasting the following in a repl:
<
TUPLE: A ;
TUPLE: C < A ;
Line 621 ⟶ 812:
C new
[ clone ]
[ serial-clone ] bi [ class . ] bi@</
{{out}}
C
C
=={{header|Forth}}==
{{works with|4tH|3.62.1}}
{{trans|Aikido}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<syntaxhighlight lang="forth">include lib/memcell.4th
include 4pp/lib/foos.4pp
( a1 -- a2)
:token fork dup allocated dup (~~alloc) swap >r swap over r> smove ;
\ allocate an empty object
:: T() \ super class T
class
method: print \ print message
method: clone \ clone yourself
end-class {
\ implementing methods
:method { ." class T" cr } ; defines print
fork defines clone ( -- addr)
}
;
:: S() \ class S
extends T() \ derived from T
end-extends { \ print message
:method { ." class S" cr } ; defines print
} \ clone yourself
;
new T() t \ create a new object t
new S() s \ create a new object s
." before copy" cr
t => print \ use "print" methods
s => print
t => clone to tcopy \ cloning t, spawning tcopy
s => clone to scopy \ cloning s, spawning scopy
." after copy" cr
tcopy => print \ use "print" methods
scopy => print</syntaxhighlight>
Works with any ANS Forth
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang="forth">include FMS-SI.f
:class T
ivar container \ can contain an object of any type
:m put ( obj -- ) container ! ;m
:m init: self self put ;m \ initially container holds self
:m print ." class is T" ;m
:m print-container container @ print ;m
;class
:class S <super T \ subclass S from T
:m print ." class is S" ;m \ override T's print method
;class
: ecopy {: obj1 -- obj2 :} \ make an exact copy of obj
obj1 dup >class dfa @
obj1 heap: dup >r swap move r> ;
T obj-t \ instantiate a T object
obj-t print-container \ class is T
S obj-s \ instantiate an S object
obj-s ecopy obj-t put \ make an exact copy of S object and store in T object
obj-t print-container \ class is S
</syntaxhighlight>
=={{header|Fortran}}==
Tested with GNU gfortran 5.2.1 and INTEL ifort 16.
<syntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
!Module polymorphic_copy_example_module
!-----------------------------------------------------------------------
module polymorphic_copy_example_module
implicit none
private ! all by default
public :: T,S
type, abstract :: T
contains
procedure (T_procedure1), deferred, pass :: identify
procedure (T_procedure2), deferred, pass :: duplicate
end type T
abstract interface
subroutine T_procedure1(this)
import :: T
class(T), intent(inout) :: this
end subroutine T_procedure1
function T_procedure2(this) result(Tobj)
import :: T
class(T), intent(inout) :: this
class(T), allocatable :: Tobj
end function T_procedure2
end interface
type, extends(T) :: S
contains
procedure, pass :: identify
procedure, pass :: duplicate
end type S
contains
subroutine identify(this)
implicit none
class(S), intent(inout) :: this
write(*,*) "S"
end subroutine identify
function duplicate(this) result(obj)
class(S), intent(inout) :: this
class(T), allocatable :: obj
allocate(obj, source = S())
end function duplicate
end module polymorphic_copy_example_module
!-----------------------------------------------------------------------
!Main program test
!-----------------------------------------------------------------------
program test
use polymorphic_copy_example_module
implicit none
class(T), allocatable :: Sobj
class(T), allocatable :: Sclone
allocate(Sobj, source = S())
allocate(Sclone, source = Sobj % duplicate())
call Sobj % identify()
call Sclone % identify()
end program test
</syntaxhighlight>
=={{header|FreeBASIC}}==
FreeBASIC does not support object-oriented programming and polymorphy. However, you can simulate it using user-defined types and procedure pointers.
<syntaxhighlight lang="vbnet">Type T
method As Sub(pthis As T Ptr)
End Type
Type S Extends T
dato As Integer
End Type
Sub TMethod(pthis As T Ptr)
Print "T method"
End Sub
Sub SMethod(pthis As S Ptr)
Print "S method, dato = "; pthis->dato
End Sub
Sub CallMethod(pthis As T Ptr)
pthis->method(pthis)
End Sub
Dim As T tt
tt.method = @TMethod
Dim As S ss
ss.method = @SMethod
ss.dato = 123
Sleep</syntaxhighlight>
{{out}}
<pre>T method
S method, dato = 123</pre>
=={{header|Go}}==
Go does not have the terminology of polymorphism, classes, inheritance, derived types, or overriding.
Line 632 ⟶ 1,002:
In addition to the types t and s called for by the task description, I define two other types:
i, an interface type, is needed as a common "base" definition for the method.
This is not Go terminology, and in fact notice that i is not even referenced anywhere in the definitions of types s or t.
A "parent" method definition is called for by the task however, and interfaces are Go's way of doing this.
r, another type defined similarly to s, I added to illustrate that this analog of method inheritance and overriding is valid. (In Go terminology, that the method set of a type with an anonymous field includes the method set of the anonymous field.)
You can see in the output that interface values of type r access t's identify method.
Values of type s would as well, except s has it's own identify method which takes precedence.
<syntaxhighlight lang="go">package main
import (
Line 674 ⟶ 1,048:
// the same method on s. although s already satisfied i, calls to identify
// will now find this method rather than the one defined on t.
// in a sense it "overrides" the method of the "base class."
func (x s) identify() string {
return "I'm an s!"
Line 718 ⟶ 1,092:
fmt.Println("i2c:", i2c, "/", i2c.identify(), "/", reflect.TypeOf(i2c))
fmt.Println("i3c:", i3c, "/", i3c.identify(), "/", reflect.TypeOf(i3c))
}</
{{out}}
<pre>
Initial (zero) values of interface variables:
Line 740 ⟶ 1,114:
i2c: {6 one} / I'm an s! / main.s
i3c: {7 0x0} / I'm a t! / main.r
</pre>
=={{header|Groovy}}==
{{trans|Java}} (more or less)
Solution:
<syntaxhighlight lang="groovy">class T implements Cloneable {
String property
String name() { 'T' }
T copy() {
try { super.clone() }
catch(CloneNotSupportedException e) { null }
}
@Override
boolean equals(that) { this.name() == that?.name() && this.property == that?.property }
}
class S extends T {
@Override String name() { 'S' }
}</syntaxhighlight>
Test:
<syntaxhighlight lang="groovy">T obj1 = new T(property: 'whatever')
S obj2 = new S(property: 'meh')
def objA = obj1.copy()
def objB = obj2.copy()
assert objA.class == T
assert objA == obj1 && ! objA.is(obj1) // same values, not same instance
assert objB.class == S
assert objB == obj2 && ! objB.is(obj2) // same values, not same instance
println "objA:: name: ${objA.name()}, property: ${objA.property}"
println "objB:: name: ${objB.name()}, property: ${objB.property}"</syntaxhighlight>
{{out}}
<pre>objA:: name: T, property: whatever
objB:: name: S, property: meh</pre>
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon do no compile-time type checks.
The deepcopy procedure from the Deep Copy task is sufficient.
The sample code shown below is Unicon-specific only because it is copying an object (Icon has no object-oriented support).
The deepcopy procedure is identical in both languages.
<syntaxhighlight lang="unicon">class T()
method a(); write("This is T's a"); end
end
class S: T()
method a(); write("This is S's a"); end
end
procedure main()
write("S:",deepcopy(S()).a())
end
procedure deepcopy(A, cache) #: return a deepcopy of A
local k
/cache := table() # used to handle multireferenced objects
if \cache[A] then return cache[A]
case type(A) of {
"table"|"list": {
cache[A] := copy(A)
every cache[A][k := key(A)] := deepcopy(A[k], cache)
}
"set": {
cache[A] := set()
every insert(cache[A], deepcopy(!A, cache))
}
default: { # records and objects (encoded as records)
cache[A] := copy(A)
if match("record ",image(A)) then {
every cache[A][k := key(A)] := deepcopy(A[k], cache)
}
}
}
return .cache[A]
end</syntaxhighlight>
Sample run:
<pre>
->polycopy
This is S's a
->
</pre>
=={{header|J}}==
Most of the time, J will automatically make a copy for you on dereference.
So expressions of the form
def=: abc
are sufficient.
Line 752 ⟶ 1,216:
Note that objects cannot be dereferenced. If you need polymorphic copy in J, you probably should not be using objects for that purpose.
=={{header|Java}}==
Here we implement a "copy" method once in the base class because there is by default no public way to copy an object from outside the class in Java. (There is a protected, not public, "clone" method inherited from Object.)
The way to clone polymorphically is to obtain a copy from the superclass's <code>clone()</code> method, and then perform custom copying operations specific to this class.
If this pattern is followed, the calls will eventually pass all the way up to <code>Object</code>'s <code>clone()</code> method, which performs a polymorphic copy.
If you do not follow this pattern, and simply use a constructor, like <code>new T()</code>, then the copy won't be polymorphic.
<syntaxhighlight lang="java">class T implements Cloneable {
public String name() { return "T"; }
public T copy() {
Line 790 ⟶ 1,245:
System.out.println(copier(obj2).name()); // prints "S"
}
}</
=={{header|JavaScript}}==
Copied from [http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone here]:
<syntaxhighlight lang="javascript">function clone(obj){
if (obj == null || typeof(obj) != 'object')
return obj;
var temp = {};
for (var key in obj)
temp[key] = clone(obj[key]);
return temp;
}</syntaxhighlight>
=={{header|Julia}}==
To perform as required in the exercise, mutable structs must be used to keep the deepcopy
procedure from being optimized away as a mere reference to the first struct.
<syntaxhighlight lang="julia">
abstract type Jewel end
mutable struct RoseQuartz <: Jewel
carats::Float64
quality::String
end
mutable struct Sapphire <: Jewel
color::String
carats::Float64
quality::String
end
color(j::RoseQuartz) = "rosepink"
color(j::Jewel) = "Use the loupe."
color(j::Sapphire) = j.color
function testtypecopy()
a = Sapphire("blue", 5.0, "good")
b = RoseQuartz(3.5, "excellent")
j::Jewel = deepcopy(b)
println("a is a Jewel? ", a isa Jewel)
println("b is a Jewel? ", a isa Jewel)
println("j is a Jewel? ", a isa Jewel)
println("a is a Sapphire? ", a isa Sapphire)
println("a is a RoseQuartz? ", a isa RoseQuartz)
println("b is a Sapphire? ", b isa Sapphire)
println("b is a RoseQuartz? ", b isa RoseQuartz)
println("j is a Sapphire? ", j isa Sapphire)
println("j is a RoseQuartz? ", j isa RoseQuartz)
println("The color of j is ", color(j), ".")
println("j is the same as b? ", j == b)
end
testtypecopy()
</syntaxhighlight>{{output}} <pre>
a is a Jewel? true
b is a Jewel? true
j is a Jewel? true
a is a Sapphire? true
a is a RoseQuartz? false
b is a Sapphire? false
b is a RoseQuartz? true
j is a Sapphire? false
j is a RoseQuartz? true
The color of j is rosepink.
j is the same as b? false
</pre>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
open class Animal(val name: String, var age: Int) {
open fun copy() = Animal(name, age)
override fun toString() = "Name: $name, Age: $age"
}
class Dog(name: String, age: Int, val breed: String) : Animal(name, age) {
override fun copy() = Dog(name, age, breed)
override fun toString() = super.toString() + ", Breed: $breed"
}
fun main(args: Array<String>) {
val a: Animal = Dog("Rover", 3, "Terrier")
val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog
println("Dog 'a' = $a") // implicitly calls Dog.toString()
println("Dog 'b' = $b") // ditto
println("Dog 'a' is ${if (a === b) "" else "not"} the same object as Dog 'b'")
}</syntaxhighlight>
{{out}}
<pre>
Dog 'a' = Name: Rover, Age: 3, Breed: Terrier
Dog 'b' = Name: Rover, Age: 3, Breed: Terrier
Dog 'a' is not the same object as Dog 'b'
</pre>
=={{header|Lua}}==
Lua does not have any formal notion of OOP principles, however there are numerous ways to build work-alikes. The basic data type for building OOP-like systems is the <code>table</code>, which are easily copied (a shallow copy suffices for this task), and easily assigned (dynamically typed). The "prototype approach" (rather than the "metamethod approach") to OOP-like seems to better illustrate the task, so here such a system is built incrementally. One method will be overridden (per task), and one inherited (stretch), to better demonstrate that part of the original copy still remains while another part was modified:
<syntaxhighlight lang="lua">T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }
function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T) S1.name=function(s) return "S1" end
function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=function(s) return "S2" end})
function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end
S3 = prototype(T, {name=function(s) return "S3" end})
print("T : "..T:tostring())
print("S1: " ..S1:tostring())
print("S2: " ..S2:tostring())
print("S3: " ..S3:tostring())
print("S3's parent: "..S3.prototype:tostring())</syntaxhighlight>
{{out}}
<pre>T : I am a T
S1: I am a S1
S2: I am a S2
S3: I am a S3
S3's parent: I am a T</pre>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">T = {}
T.foo = function()
return "This is an instance of T"
end function
S = new T
S.foo = function()
return "This is an S for sure"
end function
instance = new S
print "instance.foo: " + instance.foo
copy = {}
copy = copy + instance // copies all elements
print "copy.foo: " + copy.foo
// And to prove this is a copy, and not a reference:
instance.bar = 1
copy.bar = 2
print "instance.bar: " + instance.bar
print "copy.bar: " + copy.bar</syntaxhighlight>
{{out}}
<pre>instance.foo: This is an S for sure
copy.foo: This is an S for sure
instance.bar: 1
copy.bar: 2</pre>
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref savelog symbols binary
Line 832 ⟶ 1,439:
method name returns String
return S.class.getSimpleName
</syntaxhighlight>
=={{header|
<syntaxhighlight lang="nim">type
T = ref object of RootObj
myValue: string
S1 = ref object of T
S2 = ref object of T
method speak(x: T) {.base.} = echo "T Hello ", x.myValue
method speak(x: S1) = echo "S1 Meow ", x.myValue
method speak(x: S2) = echo "S2 Woof ", x.myValue
echo "creating initial objects of types S1, S2, and T."
var a = S1(myValue: "Green")
a.speak
var b = S2(myValue: "Blue")
b.speak
var u = T(myValue: "Blue")
u.speak
echo "Making copy of a as u; colors and types should match."
u.deepCopy(a)
u.speak
a.speak
echo "Assigning new color to u; A's color should be unchanged."
u.myValue = "Orange"
u.speak
a.speak
echo "Assigning u to reference same object as b; colors and types should match."
u = b
u.speak
b.speak
echo "Assigning new color to u. Since u,b reference the same object, b's color changes as well."
u.myValue = "Yellow"
u.speak
b.speak</syntaxhighlight>
{{out}}
<pre>creating initial objects of types S1, S2, and T.
S1 Meow Green
S2 Woof Blue
T Hello Blue
Making copy of a as u; colors and types should match.
S1 Meow Green
S1 Meow Green
Assigning new color to u; A's color should be unchanged.
S1 Meow Orange
S1 Meow Green
Assigning u to reference same object as b; colors and types should match.
S2 Woof Blue
S2 Woof Blue
Assigning new color to u. Since u,b reference the same object, b's color changes as well.
S2 Woof Yellow
S2 Woof Yellow</pre>
=={{header|Objective-C}}==
All objects inherit the <code>copy</code> method from <code>NSObject</code>, which performs copying.
But they must implement the <code>NSCopying</code> protocol (which involves implementing the <code>copyWithZone:</code> method) to actually specify how to copy.
Calling <code>copy</code> on an object that does not implement <code>copyWithZone:</code> will result in an error.
Generally, to implement copying, if your parent class does not implement <code>NSCopying</code>, you explicitly allocate a new object (using the class object <code>[self class]</code> instead of hard-coding the name of a particular class, in order to be polymorphic), and initialize it with your object's data.
If your parent class already implements <code>NSCopying</code>, and you wish to customize the copying of your class's fields, then you should get a copy from your parent object's <code>copyWithZone:</code> method, and then perform custom initialization on the copy.
<
- (void)identify;
@end
Line 860 ⟶ 1,523:
@interface S : T
@end
Line 872 ⟶ 1,534:
int main()
{
@autoreleasepool {
T *original = [[S alloc] init];
T *another = [original
[another identify]; // logs "I am an S"
}
return 0;
}</
Analogously, there is a <code>mutableCopy</code> method to get a mutable copy of the current object (e.g. if you have an NSArray object and you want an NSMutableArray with the same contents).
In this case it would have to implement the <code>NSMutableCopying</code> protocol (which involves implementing the <code>mutableCopyWithZone:</code> method) to specify how to copy.
=={{header|OCaml}}==
I decided not to use classes and inheritance here because structural subtyping is more natural in OCaml. Oo.copy is polymorphic over all object types.
<
object
method name = "T"
Line 897 ⟶ 1,561:
let () =
print_endline (Oo.copy obj1)#name; (* prints "T" *)
print_endline (Oo.copy obj2)#name; (* prints "S" *)</
=={{header|ooRexx}}==
All ooRexx objects have a copy method inherited from the object class that performs a shallow copy of the object state.
<syntaxhighlight lang="oorexx">
s = .s~new
s2 = s~copy -- makes a copy of the first
Line 914 ⟶ 1,578:
::method name
return "S"
</syntaxhighlight>
=={{header|OxygenBasic}}==
<
'======
class T
Line 955 ⟶ 1,619:
del objA : del objB
</syntaxhighlight>
=={{header|Oz}}==
We need to derive from the class <code>ObjectSupport.reflect</code> in order to have a <code>clone</code> method.
<
class T from ObjectSupport.reflect
meth init
Line 999 ⟶ 1,663:
{Obj setA(13)}
{Copy setA(14)}
{Obj getA($)} \= {Copy getA($)} = true</
Oz is not a pure object-oriented language. In fact, most values are not objects.
For immutable data it usually does not make sense to clone it because it does not have an identity beyond its value.
For mutable data types there are clone functions available (<code>Dictionary.clone</code>, <code>Array.clone</code>, <code>BitArray.clone</code>).
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
type
Base = class
public
fb: integer;
constructor (fb: integer) := Self.fb := fb;
function ToString: string; override := fb.ToString;
function Clone: Base; virtual := new Base(fb);
end;
Derived = class(Base)
public
fd: real;
constructor (fb: integer; fd: real);
begin
inherited Create(fb);
Self.fd := fd;
end;
function ToString: string; override := inherited ToString + ',' + fd.ToString;
function Clone: Base; override := new derived(fb,fd);
end;
begin
var lst := new List<Base>;
lst.Add(new Base(3));
lst.Add(new Derived(4,5.5));
lst.Add(new Base(6));
lst.Add(new Derived(7,8.8));
lst.Println;
var lst1 := new List<Base>;
foreach var obj in lst do
lst1.Add(obj.Clone);
lst1.Println;
end.
</syntaxhighlight>
{{out}}
<pre>
3 4,5.5 6 7,8.8
3 4,5.5 6 7,8.8
</pre>
=={{header|Perl}}==
<
sub new {
my $cls = shift;
Line 1,056 ⟶ 1,764:
$x->set_data('totally different');
print "\$x is: ";
$x->manifest;</
=={{header|Phix}}==
=== traditional object/sequence ===
The object type is the ultimate polymorph - there is <i>nothing</i> that you can store anywhere else that you cannot store in an object.
For this demonstration (not that this really proves much), our types T and S (overkill really) are just going to contain a string name and a method (routine_id).
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">NAME</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">METHOD</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">me_t</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"I is a T\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">me_s</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"I is an S\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">type</span> <span style="color: #000000;">T</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- as o[METHOD] can be overidden, don't verify it (as in test for me_t)!</span>
<span style="color: #008080;">return</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">[</span><span style="color: #000000;">NAME</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">and</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">[</span><span style="color: #000000;">METHOD</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<span style="color: #008080;">type</span> <span style="color: #000000;">S</span><span style="color: #0000FF;">(</span><span style="color: #000000;">T</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">METHOD</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">me_s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<span style="color: #000000;">S</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"S"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">me_s</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">T</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"T"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">me_t</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">call_proc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">METHOD</span><span style="color: #0000FF;">],{})</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
<span style="color: #7060A8;">call_proc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">METHOD</span><span style="color: #0000FF;">],{})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
I is a T
I is an S
</pre>
===classes===
{{libheader|Phix/Class}}
Not recommended or formally supported, but these sort of low-level things are perfectly possible.<br>
Note the result from get_struct_fields() is not documented and liable to change between releases.<br>
The deep_copy_class() routine also shows how to break privacy on fetch/set of private fields by faking the context (name).
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class under p2js, and certainly not the low-level stuff)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">structs</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">deep_copy_class</span><span style="color: #0000FF;">(</span><span style="color: #008080;">class</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">get_struct_name</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">fields</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">get_struct_fields</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fields</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">field</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fields</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">store_field</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">field</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fetch_field</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">field</span><span style="color: #0000FF;">,</span><span style="color: #000000;">name</span><span style="color: #0000FF;">),</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">T</span>
<span style="color: #008080;">private</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">x</span>
<span style="color: #008080;">public</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">y</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"This is T%d/%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
<span style="color: #000000;">T</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}),</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deep_copy_class</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">.</span><span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span>
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
This is T1/2
This is T1/3
</pre>
=={{header|PHP}}==
<
class T {
function name() { return "T"; }
Line 1,080 ⟶ 1,864:
echo $obj3->name(), "\n"; // prints "T"
echo $obj4->name(), "\n"; // prints "S"
?></
=={{header|PicoLisp}}==
Any object can be copied by transferring the value and the property list.
If we create an object 'A':
<
-> $385603635
Line 1,094 ⟶ 1,878:
attr2 "def"
attr1 123
-> $385603635</
Then we can easily copy it to a new object 'B':
<
Inspecting 'B':
<
$385346595 (+Cls1 +Cls2)
attr1 123
Line 1,104 ⟶ 1,888:
attr3 (4 2 0)
attr4
-> $385346595</
=={{header|Python}}==
<
class T:
Line 1,160 ⟶ 1,944:
u.myValue = "Yellow"
u.speak()
b.speak()</syntaxhighlight>
{{out}}
<pre>
creating initial objects of types S1, S2, and T
S1 Meow Green
Line 1,178 ⟶ 1,964:
S2 Woof Yellow</pre>
The foregoing example uses the Python standard library ''copy'' module.
The task, as stated,does not provide insight as to what should happen should the object contain lists of other objects.
It could be necessary to use "deep copy" instead of copy. (using ''copy.deepcopy'').
The distinction is important for complex objects containing references to other objects (for instances lists, tuples or dictionaries containing other lists, tuples or dictionaries as elements).
The described task, as presented, offers no guidance on this matter.
In many cases the most portable and robust "copy" would be made by serializing the source object and then de-serializing it back into the target.
Under Python this would best be done with the ''pickle'' or ''cPickle'' standard modules.
<
source = {'a': [1, 2.0, 3, 4+6j],
Line 1,188 ⟶ 1,979:
'c': None}
target = pickle.loads(pickle.dumps(source))</
In this example we use the ''cPickle'' module which is an implementation of the pickle features coded in C for optimal performance.
We import it as ''pickle'' since we intend to use only those features which are common to both implementations.
(The pure Python implementation is retained for those who which to create their own classes derived therefrom).
The ''dumps()'' and ''loads()'' methods dump the data structures to a string and load them from a string, respectively. (The more common use of ''pickle'' is to serialize the data out to a file or over a network connection using file-like ''.read()'' and ''.write()'' methods.
For those we'd use the ''pickle.dump()'' and ''pickle.load()'' methods).
For the simplest cases one can use simple Python introspection to copy simple objects:
<
if hasattr(source, 'items') and callable(source.items):
for key,value in source.items:
Line 1,201 ⟶ 1,996:
target = source[:]
else: # Following is not recommended. (see below).
target = source</
This example handles dictionaries (and anything that implements a sufficiently dictionary like interface to support the ''items()'' method along with the ''__setitem__()'' method. (statements of the form '''''x[y] = z''''' in Python are implicitly calling the ''__setitem__()'' method of the "x" object, passing it a key of "y" and a value of "z."
Similarly this code tests if an item is a sequence (one can call the "len()" built-in function on it) and, if so, uses a slice assignment to perform a shallow copy.
For any other type of object a simple binding is performed.
Technically this last case will not "copy" anything ... it will create a new name binding to the object to which "source" was already a reference.
The earlier binding of a "blank" instance of the source's __class__ will be replaced.
So the trick of creating the blank object of the same type is only meaningful for the other types.
In the cases of strings, integers and other numbers the objects themselves are immutable and the bindings are all dynamic (so the entire task is moot with respect to them).
=={{header|Racket}}==
===Using prefab structures===
This method is useful only for prefab structures.
<syntaxhighlight lang="racket">#lang racket/base
(define (copy-prefab-struct str)
(apply make-prefab-struct (vector->list (struct->vector str))))
(struct point (x y) #:prefab)
(struct point/color point (color) #:prefab)
(let* ([original (point 0 0)]
[copied (copy-prefab-struct original)])
(displayln copied)
(displayln (eq? original copied)))
(let* ([original (point/color 0 0 'black)]
[copied (copy-prefab-struct original)])
(displayln copied)
(displayln (eq? original copied)))</syntaxhighlight>
{{out}}
<pre>#s(struct:point 0 0)
#f
#s(struct:point/color 0 0 black)
#f
</pre>
===Using transparent structures===
This method can be applied to prefab or transparent structures, or using a powerful enough inspector. The example uses transparent structures.
It’s also possible to copy other structures using generics or structure-type-properties to implement a “magic”-like generic method.
<syntaxhighlight lang="racket">#lang racket/base
(define (copy-struct str)
(define-values (str-struct-info _) (struct-info str))
(define str-maker (struct-type-make-constructor str-struct-info))
(apply str-maker (cdr (vector->list (struct->vector str)))))
(struct point (x y) #:transparent)
(struct point/color point (color) #:transparent)
(let* ([original (point 0 0)]
[copied (copy-struct original)])
(displayln copied)
(displayln (eq? original copied)))
(let* ([original (point/color 0 0 'black)]
[copied (copy-struct original)])
(displayln copied)
(displayln (eq? original copied)))</syntaxhighlight>
{{out}}
<pre>#s(struct:point 0 0)
#f
#s(struct:point/color 0 0 black)
#f
</pre>
===Using classes===
There is no build-in clone method, so the class (or the interface) must implement it.
<syntaxhighlight lang="racket">;#lang racket
(define point%
(class object%
(super-new)
(init-field x y)
(define/public (clone) (new this% [x x] [y y]))
(define/public (to-list) (list this% x y))))
(define point/color%
(class point%
(super-new)
(inherit-field x y)
(init-field color)
(define/override (clone) (new this% [x x] [y y] [color color]))
(define/override (to-list) (list this% x y color))))</syntaxhighlight>
{{out}}
<pre>(#<class:point%> 0 0)
#f
(#<class:point/color%> 0 0 black)
#f</pre>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku" line>my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }}
my Cool $y = $x.clone;
$y.brag;</syntaxhighlight>
{{out}}
<pre>I'm a cool Rat+{Fink}!</pre>
=={{header|REXX}}==
In the REXX language, every variable is a string (whether or not they contain characters or numerals).
<br>However, a variables' type (by REXX's definition) can be determined/inferred from it's attributes (datatypes).
<syntaxhighlight lang="rexx">/*REXX program to copy (polymorphically) one variable's value into another variable. */
b= 'old value.'
a= 123.45
b= a /*copy a variable's value into another.*/
if a==b then say "copy did work."
else say "copy didn't work." /*didn't work, maybe ran out of storage*/
/*stick a fork in it, we're all done. */</syntaxhighlight>
Programming note: Most REXXes will raise a syntax error if an assignment (copy) fails, but it's not guaranteed to do so.<br><br>
=={{header|Ruby}}==
All Ruby objects inherit two methods for copying themselves: "clone" and "dup".
I don't really understand the difference between them.
<syntaxhighlight lang="ruby">class T
def name
"T"
Line 1,222 ⟶ 2,127:
obj2 = S.new
puts obj1.dup.name # prints "T"
puts obj2.dup.name # prints "S"</
=={{header|Scala}}==
<syntaxhighlight lang="text">object PolymorphicCopy {
def main(args: Array[String]) {
val a: Animal = Dog("Rover", 3, "Terrier")
val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog
println(s"Dog 'a' = $a") // implicitly calls Dog.toString()
println(s"Dog 'b' = $b") // ditto
println(s"Dog 'a' is ${if (a == b) "" else "not"} the same object as Dog 'b'")
}
case class Animal(name: String, age: Int) {
override def toString = s"Name: $name, Age: $age"
}
case class Dog(override val name: String, override val age: Int, breed: String) extends Animal(name, age) {
override def toString = super.toString() + s", Breed: $breed"
}
}</syntaxhighlight>
=={{header|Sidef}}==
''Object.dclone()'' makes a deep clone of any mutable object and returns it to the caller.
<syntaxhighlight lang="ruby">class T(value) {
method display {
say value;
}
}
class S(value) < T {
method display {
say value;
}
}
var obj1 = T("T");
var obj2 = S("S");
var obj3 = obj2.dclone; # make a deep clone of obj2
obj1.value = "foo"; # change the value of obj1
obj2.value = "bar"; # change the value of obj2
obj1.display; # prints "foo"
obj2.display; # prints "bar"
obj3.display; # prints "S"</syntaxhighlight>
=={{header|Slate}}==
All objects in Slate may be <tt>clone</tt>d unless they are clones of <tt>Oddball</tt> (like <tt>True</tt>, <tt>False</tt>, and <tt>Nil</tt>) or are word-size Integers (which are encoded as tagged pointer values).
This is a shallow copy where no values held in the object's slots are replaced with copies.
There is also a <tt>copy</tt> method which is universal and overridden to perform deep copies as appropriate - copying continues via recursion through slot values and should be modified on any type where equality (<tt>=</tt>) is overridden.
<
define: #S &parents: {Cloneable}.
Line 1,236 ⟶ 2,191:
obj1 printName.
obj2 printName.</
=={{header|Swift}}==
<syntaxhighlight lang="swift">class T {
required init() { } // constructor used in polymorphic initialization must be "required"
func identify() {
println("I am a genuine T")
}
func copy() -> T {
let newObj : T = self.dynamicType() // call an appropriate constructor here
// then copy data into newObj as appropriate here
// make sure to use "self.dynamicType(...)" and
// not "T(...)" to make it polymorphic
return newObj
}
}
class S : T {
override func identify() {
println("I am an S")
}
}
let original : T = S()
let another : T = original.copy()
println(original === another) // prints "false" (i.e. they are different objects)
another.identify() // prints "I am an S"</syntaxhighlight>
=={{header|Tcl}}==
Tcl values are logically immutable, and are passed around by reference with copies being taken as and when it is necessary to do so to maintain the immutable model.
Hence an effective copy of any value is just:
<syntaxhighlight lang="tcl">set varCopy $varOriginal</syntaxhighlight>
With objects, slightly more work is required because they are normally passed around by name/reference.
<br>
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
method clone {{name {}}} {
# Make a bare, optionally named, copy of the object
Line 1,285 ⟶ 2,267:
$obj2 rename "Hocus Pocus"
$obj2 print
$obj1 print</
<pre>
this is Abracadabra in ::oo::Obj5, stepped 2 times
Line 1,294 ⟶ 2,276:
</pre>
=={{header|TXR}}==
TXR Lisp has a <code>copy</code> function that produces copies of objects of all sorts.
Structures are shallowly copied; the <code>copy-struct</code> function is used when the
argument is a structure. Our polymorphic object can use <code>copy</code> to make a shallow copy of itself which shares a reference to the contained object. Then break the reference by calling <code>copy</code> on the object contained in the copy.
<syntaxhighlight lang="txrlisp">(defstruct base ()
(:method identify (self) (put-line "base")))
(defstruct derived (base)
(:method identify (self) (put-line "derived")))
(defstruct poly ()
obj
(:method deep-copy (self)
(let ((c (copy self))) ;; make copy of s
(upd c.obj copy) ;; copy self's obj
c))) ;; return c
;; Test
(let* ((b (new base))
(d (new derived))
(p (new poly obj d)))
b.(identify) ;; prints base
d.(identify) ;; prints derived
(let ((c p.(deep-copy)))
p.obj.(identify) ;; prints derived
(prinl (eq p.obj c.obj)))) ;; prints nil: c.obj is not a ref to p.obj</syntaxhighlight>
{{out}}
<pre>base
derived
derived
nil</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
Wren is dynamically typed and a variable therefore assumes the type of whatever object is currently assigned to it.
However, the language is class based and supports inheritance and polymorphic methods. User defined types are always reference types and one can determine whether two references refer to the same object or not by calling the Object.same method.
There is no built in 'copy' method - you need to write your own for any class that needs it.
<syntaxhighlight lang="wren">class Animal {
construct new(name, age) {
_name = name
_age = age
}
name { _name }
age { _age }
copy() { Animal.new(name, age) }
toString { "Name: %(_name), Age: %(_age)" }
}
class Dog is Animal {
construct new(name, age, breed) {
super(name, age) // call Animal's constructor
_breed = breed
}
// name and age properties will be inherited from Animal
breed { _breed }
copy() { Dog.new(name, age, breed) } // overrides Animal's copy() method
toString { super.toString + ", Breed: %(_breed)" } // overrides Animal's toString method
}
var a = Dog.new("Rover", 3, "Terrier") // a's type is Dog
var b = a.copy() // a's copy() method is called and so b's type is Dog
System.print("Dog 'a' -> %(a)") // implicitly calls a's toString method
System.print("Dog 'b' -> %(b)") // ditto
System.print("Dog 'a' is %((Object.same(a, b)) ? "" : "not") the same object as Dog 'b'")</syntaxhighlight>
{{out}}
<pre>
Dog 'a' -> Name: Rover, Age: 3, Breed: Terrier
Dog 'b' -> Name: Rover, Age: 3, Breed: Terrier
Dog 'a' is not the same object as Dog 'b'
</pre>
{{omit from|AWK|Variables are typeless, so morphing is done on assignment}}
{{omit from|GUISS}}
{{omit from|M4}}
{{omit from|Mathematica|no types}}
{{omit from|Maxima}}
{{omit from|PARI/GP}}
|