Polymorphism: Difference between revisions

Content added Content deleted
m (Minor fix)
Line 2,115: Line 2,115:


=={{header|Julia}}==
=={{header|Julia}}==
There is no obvious inheritance hierarchy here to get polymorphism. Julia has multiple dispatch, so the appropriate implementation of the print function will be called at runtime depending on the type of the arguments provided. The import of Base.print is done to allow the print function to dispatch on some new types you define.
There is no obvious inheritance hierarchy here to get polymorphism. Julia has multiple dispatch, so the appropriate implementation of the show function will be called at runtime depending on the type of the arguments provided. The declaration of Base.show is done to implicitly import the show function from the Base module and create new methods.


It would not be idiomatic to define setters and getters for a type like this in Julia. One would just access the fields directly. There is no need to explicitly define a constructor since that is automatically provided. You only roll your own if you need more elaborate initialization or you need to set default values.
It would not be idiomatic to define setters and getters for a type like this in Julia. One would just access the fields directly. There is no need to explicitly define a constructor since that is automatically provided. You only roll your own if you need more elaborate initialization or you need to set default values.


{{works with|Julia|0.6}}
<lang julia>
<lang julia>mutable struct Point

import Base.print
type Point
x::Float64
x::Float64
y::Float64
y::Float64
end
end


print(p::Point) = println("Point($(p.x), $(p.y))")
Base.show(io::IO, p::Point) = print(io, "Point($(p.x), $(p.y))")


x(p::Point) = p.x
getx(p::Point) = p.x
y(p::Point) = p.y
gety(p::Point) = p.y


setx(p::Point, x) = (p.x = x)
setx(p::Point, x) = (p.x = x)
sety(p::Point, y) = (p.y = y)
sety(p::Point, y) = (p.y = y)


type Circle
mutable struct Circle
x::Float64
x::Float64
y::Float64
y::Float64
Line 2,142: Line 2,139:
end
end


x(c::Circle) = c.x
getx(c::Circle) = c.x
y(c::Circle) = c.y
gety(c::Circle) = c.y
r(c::Circle) = c.r
getr(c::Circle) = c.r


setx(c::Circle, x) = (c.x = x)
setx(c::Circle, x) = (c.x = x)
sety(c::Circle, y) = (c.y = y)
sety(c::Circle, y) = (c.y = y)
setr(c::Circle, r) = (c.r = r)
setr(c::Circle, r) = (c.r = r)


print(c::Circle) = println("Circle($(c.x), $(c.y), $(c.r))")
Base.show(io::IO, c::Circle) = print(io, "Circle($(c.x), $(c.y), $(c.r))")</lang>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==