Program:
abstract type Shape end
# poymorhpic function computation
function area(shape::Shape)
throw(MethodError("area() is not implemented for abstract type Shape"))
end
struct Circle <: Shape
radius::Real
end
function area(c::Circle)
return 3 * c.radius ^ 2
end
struct Rectangle <: Shape
width::Real
height::Real
end
function area(r::Rectangle)
return r.width * r.height
end
struct Square <: Shape
width::Real
end
function area(s::Square)
return s.width * s.width
end
function main()
shapes = Shape[Circle(1), Square(2), Rectangle(3, 4)]
println("Area Circle(1) = ", area(shapes[1]))
println("Area Square(2) = ", area(shapes[2]))
println("Area Rectangle(3, 4) = ", area(shapes[3]))
end
main()
Output:
Area Circle(1) = 3
Area Square(2) = 4
Area Rectangle(3, 4) = 12
No comments:
Post a Comment