Constructors in Java

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:

  1. No-arg constructor: It simply means constructor with no arguments. Also called default constructor.

Syntax : className(){//code//}

Default/no-arg constructor
Output

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//}

Parameterized Constructor
Output

Important Points of Constructors:

  1. When you call a constructor while creating an object, memory for that object is allocated.
  2. Java is a complete OOP based programming language, so at least one constructor ignites when creating an object.
  3. Java compiler creates a constructor if you don’t create.
  4. Constructor is called constructor because it puts value into the object and allocates memory to it.
  5. 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:

https://www.javatpoint.com/java-constructor

https://www.javatpoint.com/object-cloning

Tech-implementer,Blogger,Web-Developer,Machine Learning Enthusiast