RosettaCodeData/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000

109 lines
2.0 KiB
Plaintext

Module Polymorphism {
Class Point {
private:
double x, y
public:
module print {
Print "x="+.x, "y="+.y
}
class:
module Point (.x, .y) {
}
}
Class Circle as Point {
private:
double r
public:
group radius {
value {
link parent r to r
=r
}
Set {
Error "No Set for radius"
}
}
module print {
Print "x="+.x, "y="+.y, "r="+.r
}
class:
module Circle (.x, .y, .r) {
}
}
Class Circle2{
{ ' a different constructor - Version 14
read xa=0, ya=0, ra=0
if ra=0 then ra=1
}
public:
Property r {
value, ' we can read it
set { ' we can change if is >0
if value<=0 then exit ' skip
}
}=ra
Point Inner(xa, ya)
// add a function to Inner to read private X and Y
Group Inner {
function readXY {
=.x, .y
}
}
Group CircleType { ' an inner object which return a value of type circle
Value { ' return a Circle type
link parent Inner to that
link parent r to ra
=Circle(!that.readXY(), ra)
}
}
module print {
(x,y)=.inner.readXY()
Print "x="+x, "y="+y, "r="+.r
}
}
A=Point(10, 20)
B=Circle(2,3,5)
doit(A)
doit(B)
print B is type Point = true
print B is type Circle = true
C=Circle2(12,13,15)
C.r=0
Print "C radius = ";C.r
print C is type Circle2 = true
doit(C.CircleType)
// Circle2 has a Point object
doit(C.Inner)
D=C.CircleType
print "D radious = ";d.radius
try {
d.radius=100
}
print error$
print D is type Point = true
print D is type Circle = true
print D is type Circle2 = false
doit(D)
doit2(&D)
doit3(pointer(D)) ' we pass a weak reference - pointer((D)) is a real pointer of a copy of D
Z->Point(10, 20) ' same as Z=Pointer(Point(10,20)), it is a real pointer
doit4(&Z)
End
sub doit(a as Point) ' pass by value
a.print
end sub
sub doit2(&a as Point) ' pass by reference
a.print
end sub
sub doit3(a as *Point) ' pass by value a pointer (weak reference or real pointer)
a=>print
end sub
sub doit4(&a as *Point) ' pass by reference a pointer (weak reference or real pointer)
a=>print
end sub
}
Polymorphism