Tips
- If you put void ahead of constructor name, it comes a method i.e when we call the class’s constructor with new ahead of it; this void constructor will not be called, instead you can call this as a normal method using dot . operator.
- Constructor implicitly returns the instance of the class
- Constructor cannot be inherited
- Constructor cannot be final
- Constructor can be overloaded but cannot be overriden
- No Copy constructor in java but you can copy using
- Creating a constructor that copies each value from an object
- Copying the reference to another
- By using clone
Rules for creating Java constructor
- Constructor name must be the same as its class name
- A Constructor must have no explicit return type
- A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
- Default constructor (no-arg constructor)
- A constructor is called “Default Constructor” when it doesn’t have any parameter.
- The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
- Parameterized constructor
- Constructor which has parameter is called parameterised constructor.
Constructor Overload
- Constructor overloading a technique where we can have any number of constructor with different parameter list.
Difference between constructor and method.
Java Constructor | Java Method |
---|---|
A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
A constructor must not have a return type. | A method must have a return type. |
The constructor is invoked implicitly. | The method is invoked explicitly. |
The Java compiler provides a default constructor if you don’t have any constructor in a class. | The method is not provided by the compiler in any case. |
The constructor name must be same as the class name. | The method name may or may not be same as the class name. |
To add :
- How new creates a new object via constructor in java
- Condition in which you are required to add a constructor in java
Important things to be noted for constructor
- Method with the same name as constructor can be created and no compile time or runtime exception will occur.