0% completed
A parameterized constructor is a constructor that accepts one or more parameters to initialize an object's member variables with specific values provided during object creation.
class ClassName { // Parameterized constructor ClassName(dataType parameter1, dataType parameter2, ...) { // Initialization code } }
Explanation:
In this example, we define a Car
class with a parameterized constructor that initializes its member variables with specific values provided during object creation.
Explanation:
Car(String brand, String color, int year)
:
This is the parameterized constructor for the Car
class. It takes three parameters: brand
, color
, and year
.
this.brand = brand;
, this.color = color;
, this.year = year;
:
The this
keyword refers to the current object. These lines assign the values of the parameters to the class's member variables.
Car myCar = new Car("Tesla", "White", 2023);
:
Creates a new Car
object named myCar
using the parameterized constructor, initializing it with the brand "Tesla", color "White", and year 2023.
myCar.displayDetails();
:
Calls the displayDetails
method to print the initialized values of myCar
.
This example demonstrates how you can create multiple Car
objects with different initial values using the same parameterized constructor.
Explanation:
Car(String brand, String color, int year)
:
The same parameterized constructor is used to initialize different Car
objects with varying values.
Car car1 = new Car("BMW", "Black", 2020);
:
Creates a Car
object car1
with brand "BMW", color "Black", and year 2020.
Car car2 = new Car("Audi", "Blue", 2021);
:
Creates another Car
object car2
with brand "Audi", color "Blue", and year 2021.
car1.displayDetails();
and car2.displayDetails();
:
Calls the displayDetails
method for both objects to print their respective initialized values.
A parameterized constructor enables the initialization of an object's member variables with specific values at the time of creation. Unlike the default constructor, which assigns default or predefined values, parameterized constructors provide the flexibility to set unique initial states for each object.
In this lesson, we explored the syntax and usage of parameterized constructors using the Car
class example. We saw how to create objects with different initial values and how the this
keyword helps in distinguishing between class members and constructor parameters.
.....
.....
.....