Constructors in JAVA
Constructor is a block of code that
is similar to the method. A constructor looks like an instance method in java
but it is not a method, because it does not have a return type. In other words,
constructor and method are different. It is called when an instance of
the class (Object) is created. At
the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of
method, which is used to initialize the object.
Every time an object is created using the new () keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by default.
Constructor has same name as the class and looks like this in a java code.
public
class
ABC
{
//This is the constructor
ABC(){
}
..
}
How does a constructor work
To understand the working of constructor, lets take an example. lets say we have
a class ABC.
When we create the object of ABC like
this:
ABC
obj =
new
ABC()
The new keyword here creates the object of class ABC and invokes the constructor to
initialize this newly created object
Types of Constructors
There are two types of constructors in Java:
-
Default constructor (no-arg constructor)
-
Parameterized constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter. and it is invoked at the time of Object creation.
Syntax of default constructor:
Classname ( ) { }
Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
|