Constructor

A constructor is a special method that is automatically called at the creation of an object. The identifier of this method is the name of the class, and nothing else is required for a method to be a constructor.
It is not necessary to explicitely define a constructor but if some processing - attributes initialization for example - is required for each instance of the class.
A constructor has always a "void" return type.

 Overriding of method allows a class to have several constructors.
Example: class Car int speed int power void Car(int p) ` this method is the constructor speed = 0 ` speed is initialized with a default value power = p ` power is initialized by an argument return /class


 Une classe peut avoir plusieurs constructeurs grâce au principe de surcharge des
méthodes.

Example of class,
with the speed and power attributs set up by the constructor of the class.
class Cas
  int speed
  int power

void car(int p)  ` this method is the constructor
  speed = 0       ` initializing the speed
  power = p        `initializing the power
  return
/class

 Exercises

 

1) Define the "demo" class demo with a constructor to initialize these variables :
x is an integer whose value is 10
y is an integer whose value is 5
t is a text holding "demo".

Answer