java constructors tutorial

Bodhak java constructors tutorial in this chapter we will discuss What is Constructor?, Constructor vs Method, Types of Constructors, Non-Parameterized Constructor,  Parameterized Constructor.

Constructor overloading, Calling constructor within another constructor of the same class (about this() call) in detail along with syntax and examples.

What is Constructor? Constructor in Java is block of code which is executed at the time of Object creation.

.

java constructors tutorial

On creation of a new instance (a new object) of a class using the new keyword, the constructor for that class is called.

Constructors are used to initializing the instance variables (fields) of an object with default values unless different values are supplied.

Constructor has the same name as the class name

A class can have more than one constructor as long as they have a different signature (i.e., different input arguments syntax).

Constructor cannot return values

Constructors are similar to methods, but with some important differences.

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

There are two types of constructors:

1) default constructor (Non-Parameterized constructor)

2) parameterized constructor

A constructor that has no parameter is known as default constructor they are Compiler Defined and User Defined.

Compiler Defined: If there is no constructor in a class, the compiler automatically creates a default constructor with the class name.

User-Defined Constructor

There are basically two rules defined for the constructor.

1) Constructor name must be same as its class name

2) Constructor must have no explicit return type

User-defined constructors are 2 type:

Without parameters. ( similar default constructor)

With parameters.

if we are creating the no parameter constructor in the class. It will be invoked at the time of object creation.

If A constructor is defined with parameters then it is known as parameterized constructor. The declaration is similar to method declaration.

Parameterized constructor is used to provide different values to the distinct objects.