I want to switch OOP from C++ to Julia. Please guide what is the Julia way of OOP?
In OOP in C++, classes can have member variables, or properties. These properties can have attributes like “private” or “protected”. Also member functions, or methods, can have these attributes.
In Julia, as far as I know, there are stucts or composite types, but no classes. There are no methods, but there is multiple dispatch.
My question, is there “private” and “protected” attributes for properties or methods? Can a function be a friend to a class (as C++) so that this function can access the private/protected properties?
There are no methods bound to a specific type as in class-based OOP languages, but they’re still called methods since they can be inherited from abstract super-types.
Currently no, everything is essentially public (though you can use underscores to discourage access, as in Python).
It’s not really feasible to do OOP in Julia, classes just don’t exist. There’s types, but they’re not namespaces like classes are in other languages. Julia modules are namespaces, and the exports are somewhat like public properties.
However, true access modifiers do not exist, it’s more of a recommendation. Your public API can provide getter methods preferred over internal fields, you can overload Base.getproperty to affect what instance.field syntax does, but there are commonplace methods to access any property you want. This isn’t a characteristic of non-OOP, Python is OO and also lacks true access modifiers.
You may change your way of thinking in Julia. Modules are namespaces, define your types using structs, use abstract data types for inheritence. Use multiple-dispatch to define functions that work on your specific type. That’s
func(obj, params)
instead
obj.func(params)
You will end up with a clean design and see how things are better managed.
As others in this thread have said, Julia is not an object oriented language, so to write good Julia code you will eventually need to change the way that you structure your code.
Specifically private/protected fields can often be approximated with closures (but note that nothing is completely private in Julia, as far as I know, internal fields in closures can still be accessed).
The properties of ordinary structs are immutable and cannot have attributes. It is possible to declare a struct mutable and in this case any property can have the const attribute making it immutable, e.g.
mutable struct Abc
const a::Integer
b
c::Float64
end