Java Constructors

Java Constructors

In this tutorial, we'll delve into constructors, which are fundamental for initializing objects in Java. By the end of this session, you'll have a solid understanding of what constructors are and how to use them effectively.

What is a Constructor?

  • A constructor is a special method that initializes an object when it's created.
  • It's like setting up a new car with its make, model, and features as soon as it rolls off the assembly line.
Example
class Car {
    String make;
    String model;

    // Constructor
    Car(String make, String model) {
        this.make = make;
        this.model = model;
    }
}

Car myCar = new Car("Toyota", "Camry");

Default Constructors:

  • If you don't define any constructors in your class, Java provides a default constructor with no arguments.
  • It's like a car coming off the assembly line with no additional features by default.
Example
class Car {
    String make;
    String model;
}

Car myCar = new Car(); // Default constructor is called

Parameterized Constructors:

  • You can create constructors with parameters to initialize object attributes during creation.
  • It's like specifying the car's make and model as it's being built.
Example
class Car {
    String make;
    String model;

    // Parameterized Constructor
    Car(String make, String model) {
        this.make = make;
        this.model = model;
    }
}

Car myCar = new Car("Toyota", "Camry");

Overloading Constructors:

  • You can have multiple constructors in a class with different parameter combinations.
  • It's like offering different car models with various features.
Example
class Car {
    String make;
    String model;

    // Constructor 1
    Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    // Constructor 2
    Car(String make) {
        this.make = make;
        this.model = "Unknown";
    }
}

Car car1 = new Car("Toyota", "Camry");
Car car2 = new Car("Honda");

Calling One Constructor from Another (Constructor Chaining):

  • You can call one constructor from another in the same class using this().
  • It's like a car with optional features that you can add one at a time.
Example
class Car {
    String make;
    String model;

    // Constructor 1
    Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    // Constructor 2 (calls Constructor 1)
    Car(String make) {
        this(make, "Unknown");
    }
}

Car car = new Car("Honda");

Contact Us

Name
Email
Mobile No:
subject:
Message: