0% completed
Understanding the Constructor and Default Constructor
On This Page
What is a Constructor?
Syntax of a Constructor
Example: Car Class with Constructor
What is a Default Constructor?
Example: Animal Class with Default Constructor
In this lesson, we will learn about the constructor and then about the default constructor.
What is a Constructor?
In Java, a constructor is a special method invoked when an object is created.
- Characteristics:
- Has the same name as the class.
- Does not have a return type.
Syntax of a Constructor
class ClassName { // constructor ClassName() { // Initialization code (optional) } }
Explanation:
- ClassName(): The constructor method with the same name as the class and no parameters.
- Initialization code (optional): Code inside the constructor can initialize member variables or perform other setup tasks. This part is optional; if omitted, member variables receive their default values.
Example: Car Class with Constructor
In this example, we define a Car class with a no-argument constructor that initializes its member variables.
Explanation:
Car(): Here, we have written a no-argument constructor for theCarclass.brand = "Unknown";,color = "Unpainted";,year = 0;: These lines assign default values to the class member variablesbrand,color, andyearrespectively.Car myCar = new Car();: This line creates a newCarobject namedmyCarusing this no-argument constructor.myCar.displayDetails();: Calls thedisplayDetailsmethod to print the initialized values ofmyCar.
Now, let's understand the default constructor.
What is a Default Constructor?
A default constructor is an automatically provided constructor by the Java compiler if no constructors are defined in the class. It initializes object variables with default or specified values.
Example: Animal Class with Default Constructor
This example demonstrates a default constructor in the Animal class.
Explanation:
- We don't have a constructor defined in the class. So, the Java compiler adds a default constructor, and
new Animal()calls it. Animal myAnimal = new Animal();: Creates a newAnimalobject namedmyAnimalusing the default constructor.myAnimal.displayInfo();: Calls thedisplayInfomethod to print the initialized values ofmyAnimal.
A default constructor is a no-argument constructor automatically provided by Java if no other constructors are present in the class. It initializes object member variables with default values. Understanding default constructors is essential for ensuring objects start with a consistent state, especially when no specific initialization is required.
Reading Progress
0%
On This Page
What is a Constructor?
Syntax of a Constructor
Example: Car Class with Constructor
What is a Default Constructor?
Example: Animal Class with Default Constructor