Java Class – Constructor

Finally. the component of class we will look at is Constructor. Constructors are used when creating an object of class, and it has a similar format as method. The difference is that it runs when creating an object and it does not have a return value. The syntax of constructor is as follows.

accessModifiers className (parameterList) {

}

The value of access modifiers will be something like public and private. Constructors always have the same name as the class name. The code below shows an example of MemberInfo class constructor.

Snip20150518_3

Constructor is used when creating an object with “new”. The following code is an example creating object using MemberInfo constructor.

Snip20150518_4

If you run a constructor using “new”, object is created. In other words, in above code, if you run a MemberInfo() constructor, MemberInfo() object is created and it is assigned to “info” reference. If you create an object, you can use it using a reference refering to the object.

Default constructor (created automatically)

There are 3 steps in creating an object of class.

  1. Distributing memory space for the object
  2. Initializing member variables using initializer
  3. Running constructor — our topic

An object is created after a call to constructor. In other words, the constructor must be called to create an object (instance).  To prevent the case programmer does not create a constructor, the c++ compiler automatically creates “default constructor”.

* Default constructor does not have any parameters, it does not return anything. It is not void though.

If you create a class that looks like this:

Snip20150502_13 Notice there isn’t a constructor. Then, c++ compiler automatically creates a default constructor. So the above example is same as,

Snip20150502_14