Description of Constructor with an example

Posted By :Kajal Singh |31st August 2018

Description of Constructor

1. Putting the values into the data members of an object while creating this process is known as object initialization.

2. The constructor is the special member function of a class that is used to initialize the object.

3. The Constructor is not used to creating an object, it initializes the object.
Example:

class ConstructorExample {
int salary;
ConstructorExample() {
this.salary = 1500;
System.out.println("Salary :"+salary);
}
public static void main(String arg[]) {
ConstructorExample obj = new ConstructorExample();
}
}

4. If you want successfully compile to perform any task only once in the life cycle of an object then also use the constructor.

5. If you want to provide certain common resources to each object of your class then also used the contractor.

6. There are two types of the contractor:-
1. Default constructor or non-parameterized constructor
2. Parameterised constructor

Example of Default constructor:-

class Temp {
Temp() {
System.out.println("Default Constructor");
}
public static void main(String arg[]) {
new Temp();
}
}

Example of the Parameterised constructor:-

class Temp {
void show() {
System.out.println("Show");
}
Temp(int x, int y) {
System.out.println("Parameterised Constructor");
System.out.println("x :"+x +" y :"+y);
}
public static void main(String arg[]) {
Temp t = new Temp(10, 20);
t.show();
}
}

7. No class can exist without any constructor.

8. If there is no constructor in a class, then one non-parametrized constructor (default) is inserted into the class by the compiler.

9. Whenever you want to initialize the data member of each object with a different 2 values, then always use the parameterized constructor and this concept is known as dynamic initialization of non-static data members.

Example:-

class Temp {
int x;
int y;
Temp(int x, int y) {
this.x = x;
this.y = y;
}
void show() {
System.out.println("x :"+x);
System.out.println("y :"+y);
}
public static void main(String arg[]) {
Temp t1 = new Temp(10, 20);
t1.show();
Temp t2 = new Temp(100, 200);
t2.show();
}
}

10. In Java, we can also call the methods of the class to initialize the data members of that class.

Example:-

class Temp {
int x = getX();
int getX() {
System.out.println("x :"+x);
return 20;
}
Temp() {
x = getX();
System.out.println("x :::"+x);
}
public static void main(String arg[]) {
new Temp();
}
}

11. By nature in java constructors are an implicitly static function.

12. In Java, you can also make a method with the same name as your class name.


About Author

Kajal Singh

Kajal is very sincere and hardworking. She is positive and a good team player.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us