Constructors in Java
The constructors are basically a block of code that gets into action when an object of a class is created. We call the constructor mainly using the “new” keyword.For eg: Human h1 = new Human().
Java constructors are basically is of two types:
- No-arg constructor: It simply means constructor with no arguments. Also called default constructor.
Syntax : className(){//code//}
It’s fine if you don’t create a Human Constructor here because Java will automatically create the constructor for the class.
2. Parameterized constructor: Constructor with arguments.
Syntax : className(datatype var_name ,data_type var_name,…){//code//}
Important Points of Constructors:
- When you call a constructor while creating an object, memory for that object is allocated.
- Java is a complete OOP based programming language, so at least one constructor ignites when creating an object.
- Java compiler creates a constructor if you don’t create.
- Constructor is called constructor because it puts value into the object and allocates memory to it.
- The default constructor gives default values to the object’s parameters. Eg: like int(by default “zero”), String(by default “null”).
Constructor Overloading:
Overloading defines the same method name but a different number of parameters. In the same way, you can achieve overloading in the constructor.
Copy values from one object to other
Direct Assigning values
Use of constructor
Clone method()
Cloning creates an exact copy of an object without using extra processing power.
Object.clone() methods allow doing cloning of an object.
References: