Saturday 9 April 2016

Julia: Outer Vs Inner constructor methods

In previous post, I explained about constructors in Julia. There are two ways to define constructors for a type.

a.   Outer constructor methods
b.   Inner constructor methods

a. Inner constructor methods
Inner constructor is defined inside the type declaration. It has access to the special inbuilt function new(), which is used to instantiate objects.
julia> type Employee
           id::Int64
           firstName::AbstractString
           lastName::AbstractString
           salary::Float64

           function Employee()
               this = new()

               this.id=-1
               this.firstName="no_name"
               this.lastName="no_name"
               this.salary=-1

               return this
           end

           function Employee(id::Int64, firstName::AbstractString, lastName::AbstractString, salary::Float64)
               this = new()

               this.id = id;
               this.firstName = firstName
               this.lastName = lastName
               this.salary = salary

               return this
           end
       end

Type Employee defined two inner constructors. Once a type is declared there is no way to add inner constructors to it.

b. Outer constructor methods
Outer constructors are defined outside of the type definition. Outer constructor methods depend on inner constructor methods to instantiate an object.
julia> type Dimension
           x
           y
           z

           function Dimension(x, y, z)
               this = new()
               this.x = x
               this.y = y
               this.z = z
           
               return this
           end
       end

julia> Dimension(x) = Dimension(x, x, x)
Dimension

julia> Dimension(x, y) = Dimension(x, y, 10)
Dimension

julia> dim1 = Dimension(10, 20, 30)
Dimension(10,20,30)

julia> dim2 = Dimension(20)
Dimension(20,20,20)

julia> dim3 = Dimension(1.1, 2.2)
Dimension(1.1,2.2,10)

julia> print(dim1.x, "\t",dim1.y, "\t", dim1.z)
10  20  30
julia> print(dim2.x, "\t",dim2.y, "\t", dim2.z)
20  20  20
julia> print(dim3.x, "\t",dim3.y, "\t", dim3.z)
1.1 2.2 10


‘Dimension(x)’, ‘Dimension(x,y)’ are the outer constructor methods for the type Dimension.



Previous                                                 Next                                                 Home

No comments:

Post a Comment