Java Constructors
In Java, a Constructor is a special type of method that is called when a new object of a class is created. Its main purpose is to provide initial values for the object's instance variables.
Characteristics of Constructors
- Name matches class name: The constructor's name must exactly match the name of the class it belongs to.
- No return type: Constructors have no return type, not even
void. This is a key difference from regular methods. - Automatically called: When an instance of a class is created using the
newkeyword, the constructor is automatically called.
Default Constructor
If you don't define any constructor in your class, the Java compiler automatically provides a no-argument default constructor with an empty body. This constructor initializes instance variables to their default values (0 for numbers, false for booleans, null for reference types).
Important: Once you define any constructor in your class (with or without parameters), the compiler will not provide the default constructor anymore.
Parameterized Constructor
Usually, we want to set meaningful initial values for object attributes when creating them. This can be achieved by defining constructors with parameters.
The this Keyword
In the example above, the line this.name = dogName;:
this.namerefers to the instance variablenameof the current object being created.dogNamerefers to the local parameterdogNamepassed to the constructor.
When parameter names and instance variable names are the same, you must use the this keyword to disambiguate. This is a very common coding style.
Constructor Overloading
Like regular methods, constructors can also be overloaded. This means a class can have multiple constructors, as long as their parameter lists are different (different in number, type, or order of parameters).
This provides greater flexibility for creating objects.
By overloading constructors, we can conveniently create objects that meet requirements based on different initial information.