Hello,
I am trying to understand how the Object Oriented paradigm should be implemented in Julia, coming from a C++ approach. I bought the excellent new ebook “Julia: High Performance Programming” from Packt Publishing, but only a few pages are allocated to explaining custom types.
So, I have the following example (that doesn’t work) and I would like some help on some specific questions and how to frame it for best practices in Julia:
File Shoes.jl:
type Shoes
shoesType::String
colour::String
end
In C++ I normally place each class on its own file. I am a bit lost how type hierarchy interacts with module/package hierarchy.
Should I wrap all my types in a module MyType type MyType [...] end end
fashion instead ?
File Person.jl
abstract Person
myname::String
age::Int8
end
I know this is wrong, because abstract types in Julia do not hold attributes, but which is the alternative? Create a normal type ? What I would like to achieve here is declaring a type that, while having some attributes shared by all its subtypes, it can not be instantiated, that is any objects bust be instantiated instead by a subtype (this is the meaning of abstract classes in C++)
File Student.jl:
include("Person.jl")
include("Shoes.jl")
type Student <: Person
school::String
shoes::Shoes
function printMyActivity()
println("I study at $school school")
end
end
File Employee.jl:
include("Person.jl")
include("Shoes.jl")
type Employee <: Person
monthlyIncomes::Float32
company::String
shoes::Shoes
function printMyActivity()
println("I work at $company company")
end
end
Here I have two concerns:
a) How can I avoid that the same file is included several times (that is, which is the equivalent of #ifndef
/ #define
/ #endif
?)
b) How do I bind a function to a specific type (that is, create a method in C++) ? Also in this example the same function name is associated to two different implementations based on the the type of the objects. C++ (using pointers) can use this to implement run-time polymorphism. I understood Julia obtains the same (multiple-dispach?) using the argument signature of a function, but is it possible to get it also using the type of the calling object, or this concept doesn’t exists in Julia ?
File Main.jl
include("Person.jl")
include("Shoes.jl")
include("Employee.jl")
include("Student.jl")
gymShoes = Shoes("gym","white")
proShoes = Shoes("classical","brown")
Marc = Student("Divine School",gymShoes)
MrBrown = Employee("ABC Corporation Inc.", proShoes)
Marc.printMyActivity()
MrBrown.printMyActivity()
If I run the above file I have lot of nondefined errors. When I include, am I not already using the global namespace ?
In general, I would like to understand how this simple example should be reframed to match Julia (and not C++) OO paradigm, thank you.