Crystal-Lang-02

Crystal-Lang-02

A constructor in Crystal is a special method of a class that automatically gets invoked whenever an instance of the class is created. It is responsible for initializing the object's state. In Crystal, the constructor method is named initialize. When an object is created using the new keyword, the initialize method is called, allowing us to set up the initial state of the object.

class MyDemo
  def initialize(parameter)
    @attribute = parameter
  end
end
# Creating an object and invoking the constructor
obj = MyDemo.new("example")

In this example, the initialize method sets the at attribute instance variable with the provided parameter when an object is instantiated.
Important points to remember about Constructors:

Constructors are used to initializing the instance variables.

In Crystal, the constructor has a different name, unlike other programming languages.

A constructor is defined using the initialize and def keywords. It is treated as a special method in Crystal.

Constructors can’t be overloaded in Crystal.

Constructors can’t be inherited.

It returns the instance of that class.

# constructor
def initialize()

 # instance variable @
 # class variable  @@
   @Var1 = "GeeksforGeeks"
   @Var2 = "Sudo Placement"
end

# defining method display
def display()
 puts "Value of First instance variable is: #{@Var1}"
 puts "Value of Second instance variable is : #{@Var2}"
end
end

# creating an object of Demo
obj = Demo.new()

# calling the instance methods of Demo
obj.display()

output:
Value of First instance variable is: GeeksforGeeks

Value of Second instance variable is: Sudo Placement

source:geeksforgeeks