0% completed
In this lesson, we will learn about the constructor and then what is default constructor.
In Java, a constructor is a special method invoked when an object is created.
class ClassName { // constructor ClassName() { // Initialization code (optional) } }
Explanation:
In this example, we define a Car
class with a default constructor that initializes its member variables.
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.
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.
This example demonstrates a default constructor in the Animal
class.
Explanation:
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.
.....
.....
.....