Constructor in Java

 Constructor in Java

- constructor is a special member function of a class used to initialize instance variables of a class.

- Constructors are primarily used to initialize objects of a class.

- The purpose of a constructor is to perform the initialization of data fields of an object in the class.

- Constructors can also accept arguments like methods and can be overloaded.

-  If we try to create an object of the class without specifying any constructor in the class, compiler automatically create a default constructor for us.

- creation of constructor is an optional . 



Characteristics of Java Constructor

1. Constructor’s name must be exactly the same as the class name in which it is defined. 

2. The constructor should not have any return type even void also because if there is a return type then JVM would consider as a method, not a constructor.

3. Java constructor may or may not contain parameters.

4. Whenever we create an object/instance of a class, the constructor automatically calls by the JVM . If we don’t define any constructor inside the class, Java compiler automatically creates a default constructor at compile-time.


Types of Constructors in Java

1.Default Constructor

2.Non-parameterized constructor

3.Parameterized Constructor



1. Default Constructor

- A constructor that has no parameter is known as default constructor in Java.

- When a class does not declare a constructor, Java compiler automatically adds a constructor for that class.


2. Non-parameterized Constructor

- A constructor which has no parameters in the parentheses but contains statements inside its body is called a non-parametrized constructor.


Ex :

public class Person 

 { 

// Declaration of instance variables. 

   String name; 

   int age; 

   String address; 


// Declare a non-parameterized constructor. 

   Person() 

   { 

// Initializing values to instance variables. 

     name = "Vivek"; 

     age = 25; 

     address = "Gandhi Nagar"; 

   } 


3.Parameterized Constructor

- A constructor that takes one or more parameters is called parameterized constructor in Java.

- In the parameterized constructor, instance variables automatically initialize at runtime when we pass values to parameters during object creation.

- We cannot define two constructors with the same number of parameters and the same types.


Ex :

Person(String name, int age) {

 // Constructor code.

}


Comments

Popular Posts