Polymorphic copy: Difference between revisions
Content added Content deleted
(Added Algol 68) |
(Added Wren) |
||
Line 2,127: | Line 2,127: | ||
this is Hocus Pocus in ::oo::Obj6, stepped 3 times |
this is Hocus Pocus in ::oo::Obj6, stepped 3 times |
||
this is Abracadabra in ::oo::Obj5, stepped 2 times |
this is Abracadabra in ::oo::Obj5, stepped 2 times |
||
</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. |
|||
<lang ecmascript>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'")</lang> |
|||
{{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> |
</pre> |
||