Please click on ads

Please click on ads

Monday, 19 October 2020

Java constructor

It is not mandatory for the coder to write a constructor for the class. It can be seen as a 

readily available, implicit method in every class.

The coder can write a constructor in a class, if required.

If a user defined constructor is available, it is called just after the memory is allocated for the 

object.

If no user defined constructor is provided for a class, the implicit constructor initializes the 

member variables to its default values

– numeric data types are set to 0

– char data types are set to null character(‘\0’)

– boolean data types are set to false

– reference variables are set to null

The user defined constructor is usually used to initialize the data members of the objects to

some specific values, other than the default values

A constructor method-

– will have the same name as that of the class

– will not have any return type, not even void

Types of java contructor

Default constructor (no-arg constructor)

– Parameterized constructor

Default constructor-

Compiler is responsible to generate default constructor(but not JVM).

If we are not writing any constructor then only compiler will generate default constructor.

And if we write a constructor with arguments or no-argument then compiler does not create 

default constructor.

Syntax of default constructor

<class_name>()

{

}

Parameterized Constructor-

A constructor that has parameters is known as parameterized constructor. If we want to 

initialize fields of the class with your own values, then use parameterized constructor.

Overloaded Constructor

Within a class we can declare multiple constructor and all these constructors having same name 

but different types of arguments.

Overloaded constructor is called based upon the parameters specified when new is executed

No comments:

Post a Comment