abstract type Elf end
struct LightElf <: Elf
name::String
life::Int32
end
struct DarkElf <: Elf
name::String
life::Int32
# This attribute is only in DarkElf.
enchantment::Int32
end
amber = LightElf("Amber",100)
charles = DarkElf("Charles",20,45)
elves = Elf[]
push!(elves,amber,charles)
charles = DarkElf("Charles",20,45)
println(elves[2].enchantment)
> 45
Why can I access the enchantment field from charles when it's being stored in an array of abstract Elf objects?
In a language like C# or Java, a parent would not know about any attributes specific to that sub class. Obviously, we don't have abstract classes, so we don't know what attributes will make a generic Elf. I guess you could ask, how does Julia know about the attributes that are in a struct?