Java Intermediate

0% completed

Previous
Next
Understanding the Constructor and Default Constructor

In this lesson, we will learn about the constructor and then what is 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.
Image

Example: Car Class with Constructor

In this example, we define a Car class with a default constructor that initializes its member variables.

Java
Java

. . . .

Explanation:

  • Car(): Here, we have created the default constructor for the Car class.
  • brand = "Unknown";, color = "Unpainted";, year = 0;: These lines assign default values to the class member variables brand, color, and year respectively.
  • Car myCar = new Car();: This line creates a new Car object named myCar using the default constructor.
  • myCar.displayDetails();: Calls the displayDetails method to print the initialized values of myCar.

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.

Java
Java

. . . .

Explanation:

  • We don't have a constructor defined in the class. So, Java compiler will invoke the default constructor.
  • Animal myAnimal = new Animal();: Creates a new Animal object named myAnimal using the default constructor.
  • myAnimal.displayInfo();: Calls the displayInfo method to print the initialized values of myAnimal.

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. Understanding default constructors is essential for ensuring objects start with a consistent state, especially when no specific initialization is required.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next