Constructor in Java
Constructor in Java
A Constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling the constructor, memory for the object is allocated in the
memory. It is a special type of method that is used to initialize the object. Every time an object
is created using the new() keyword, at least one constructor is called.
1. Default Constructor:
A constructor that has no parameters is known as default the constructor. A default constructor
is invisible. And if we write a constructor with no arguments, the compiler does not create a
default constructor. It is taken out. It is being overloaded and called a parameterized
constructor. The default constructor changed into the parameterized constructor. But
Parameterized constructor can’t change the default constructor. The default constructor can be
implicit or explicit. If we don’t define explicitly, we get an implicit default constructor. If we
manually write a constructor, the implicit one is overridden.
Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
this.name = name;
this.age = age;
Person person1 = new Person("Alice", 30); // Create a new Person object using the
constructor
// Call the displayInfo method to print the details of the person
person1.displayInfo();
}
}
Output
Name: Alice
Age: 30