Constructor in Java with EXAMPLE
What is Constructor in Java?
A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation. It is not mandatory for the coder to write a constructor for a class.
If no user-defined constructor is provided for a class, compiler initializes member variables to its default values.
Step 2) Save, Compile & Run the Code.
Step 3) Error = ?. Try and debug the error before proceeding to next step.
Step 4) Every class has a default Constructor. Default Constructor for class Demo is Demo(). In case you do not provide this constructor the compiler creates it for you and initializes the variables to default values. You may choose to override this default constructor and initialize variables to your desired values as shown in Example 1.
But if you specify a parametrized constructor like Demo(int a), and want to use the default constructor Demo(), it is mandatory for you to specify it.
In other words, in case your Constructor is overridden, and you want to use the default constructor, its need to be specified.
Step 5) Uncomment line # 4-8. Save, Compile & Run the code.
Consider a scenario where a base class is extended by a child. Whenever an object of the child class is created, the constructor of the parent class is invoked first. This is called Constructor chaining.
Example 3: To understand constructor chaining
Step 1) Copy the following code into the editor.
Step 2) Run the Code. Owing to constructor chaining, when the object of child class DemoChild is created, constructor Demo() of the parent class is invoked first and later constructor DemoChild() of the child is created. Expected Output =