Polymorphism: Difference between revisions

m
Switch to header template
m (→‎[[Java]]: Use Java header instead)
m (Switch to header template)
Line 2:
 
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
==[[{{header|Ada]]}}==
[[Category:Ada]]
This example is constructed using a parent package and a child package. The parent package defines the Point type. The child package defines the Circle type.
 
Line 240 ⟶ 239:
 
 
==[[{{header|BASIC]]}}==
[[Category:BASIC]]
 
* See [[Polymorphism (BASIC)]]
 
==[[{{header|C]]}}==
[[Category:C]]
* See [[Polymorphism (C)]]
 
Line 380 ⟶ 376:
}
 
==[[{{header|C sharp|C#]]}}==
[[Category:C sharp]]
 
using System;
class Point
Line 419 ⟶ 413:
}
 
== {{header|Common Lisp }}==
[[Category:Common Lisp]]
 
(defclass point ()
((x :initarg :x :initform 0 :accessor x)
Line 446 ⟶ 438:
(print-shape c))
 
== [[{{header|E]] }}==
[[Category:E]]
 
def makePoint(x, y) {
def point implements pbc {
Line 480 ⟶ 470:
println(c)
 
== [[{{header|Haskell]] }}==
[[Category:Haskell]]
Polymorhism is achieved through the type class Show
 
Line 553 ⟶ 542:
}
 
== [[{{header|OCaml]] {{header|==
[[Category:OCaml]]
 
class point ?(x=0.0) ?(y=0.0) () = (* extra () used to erase the optional parameters *)
object
Line 597 ⟶ 584:
print (new point ~y:2.1 ())
 
==[[{{header|Perl]]}}==
[[Category:Perl]]
What polymorphic function means in the context of Perl is as clear as mud. subs already can take anything as parameter by default. Destructors are automatic, so I dropped them.
{
Line 685 ⟶ 671:
};
 
==[[{{header|Pop11]]}}==
[[Category:Pop11]]
 
When class is defined in Pop11 it automatically defines default
constructors, slot accessors and copy operations. So it is enough
Line 721 ⟶ 705:
print(instance2);
 
== [[{{header|Python]] }}==
[[Category: Python]]
 
Multiple constructors are not needed because Python supports default values for arguments. Accessors are not needed because Python attributes are public. It is possible to add managed attributes later without changing the interface and existing client code. For the print function, use the standard __repr__ methods, used when printing an object. Destructors are not needed of course.
 
Line 779 ⟶ 761:
</pre>
 
== [[{{header|Ruby]] }}==
[[Category:Ruby]]
 
We use attr_accessor to provide all the accessor and assignment operations. Default arguments eliminate the need for multiple constructors. The built-in puts uses the object's to_s method.