- 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 constructor, memory for the object is allocated in the memory.
- Constructor is used to initialize the non-static value variables.
- 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.
Rules for creating Java constructor
There are two rules defined for the constructor.
- Constructor name must be the same as its class name
- A Constructor must have no explicit return type
- public,private& default key access in constructor.
Types of Java constructors
There are three types of constructors in Java:
- Default constructor
- no-argument constructor (or) zero argument constructor
- parameterized constructor
Java Default Constructor
A constructor is called “Default Constructor” when it doesn’t have any parameter.
- default constructor invisible in all classes
zero argument constructor
Java No-Arg Constructors Similar to methods, a Java constructor may or may not have any parameters (arguments). If a constructor does not accept any parameters, it is known as a no-argument constructor.
example:
class Shop
{
Shop()
{
System.out.println("hi");
}
parameterized constructor
A Constructor with arguments (or you can say parameters) is known as Parameterized constructor. As we discussed in the Java Constructor tutorial that a constructor is a special type of method that initializes the newly created object. We can have any number of Parameterized Constructor in our class.
Example
class Shop
{
Shop(int p,int d)
{
price = p;
discount = d;
}
constructor overloading
Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.
Example program
class Shop
{
Shop()
{
System.out.println("for prod3");
}
Shop(int p,int d)
{
price = p;
discount = d;
}
public static void mian(String[] args)
{
Shop prod1 = new Shop(10,2);
Shop prod2 = new Shop(20,3);
Shop prod3 = new Shop();
prod1.buy();
prod2.buy();
}
public void buy()
{
System.out.println("price is"+ price);
System.out.println("Discount is"+ discount);
}
}