In this article we learn the what is constructor in java, how to write constructor, types of constructor and what is the difference between constructor & method.
What is Constructor in Java?
A Constructor in java is a member function which has the same name as its class and is used to initialize the object of that class type with the legal initial value.
We can use the constructors when we want to assign values to the class variables at the time of object creation.
Note: When we create an object of a class, at least one constructor is called. If we do not write any constructor in the class, then the default constructor is called.
Rules for Writing Constructor in Java
1) The name of the constructor must be the same as the name of its class.
2) A constructor must have no return type. It cannot have not even void as its return type.
3) We can use the access modifiers with a constructor to control its access so that other classes can call the constructor.
4) We cannot declare a constructor as final, abstract, abstract and synchronized.
5) We can have constructors in classes and abstract classes but not in interfaces.
6) We can overload a constructor, but we can’t override a constructor.
Types of Constructor in Java
1. Default Constructors in Java
A Default Constructor is a constructor with no parameter. The Java compiler automatically creates a default constructor if we do not write any constructor in our program.
2. Parameterized Constructor in Java
A Parameterized constructor is a constructor with a specific number of parameters. We can use parameterized constructor mainly to initialize the members of the class with different values or objects.
Chaining of Constructor in Java
Constructor Chaining in Java is a process in which a constructor calls another constructor of the same class with the current/present object. The concept of constructor chaining helps to pass the parameters through different constructors, but with the same object.
Constructor chaining is the process of calling a sequence of constructors. We can do it in two ways:
1) By using this () keyword for chaining constructors in the same class
2) By using super () keyword for chaining constructors from the parent class
Differences between constructor and method
The constructor initializes an object of the class whereas the method exhibits the functionality of an object.
Constructors are invoked implicitly when the object is instantiated whereas methods are invoked explicitly by calling them.
The constructor does not return any value whereas the method may or may not return a value.
In case a constructor is not present in the class, the Java compiler provides a default constructor. But, in the case of a method, there is no default method provided.
The name of the constructor should be the same as that of the class. But the Method name should not be of the same name as that of class.