Write a Program to implement constructor in Java ?

Write a Program to implement a constructor in Java?


Example Image of Write a Program to implement constructor in Java ?
Example Image of Write a Program to implement constructor in Java?



    Key points about constructors in Java:

Name: The constructor method has the same name as the class it belongs to.

No return type: Unlike regular methods, constructors do not have a return type, not even void.

Initialization: Constructors are used to initialize the state of an object, such as setting initial values for instance variables.

Automatic Invocation: When an object is created using the new keyword, the constructor of the class is automatically called.

Overloading: Like regular methods, constructors can be overloaded, which means a class can have multiple constructors with different parameters.

Default Constructor: If you do not explicitly define any constructors in your class, Java provides a default constructor with no arguments.

Access Modifiers: Constructors can have access modifiers like public, private, protected, or default (no modifier). This determines the visibility of the constructor.

Chaining Constructors: In Java, constructors can also call other constructors within the same class using this() keyword, which is known as constructor chaining.

 Certainly! Here's an example of a Java program that demonstrates constructors:


java

class Car {

    String brand;

    String model;

    int year;


    // Constructor with parameters

    public Car(String brand, String model, int year) {

        this.brand = brand;

        this.model = model;

        this.year = year;

    }


    // Method to display car information

    public void displayInfo() {

        System.out.println("Brand: " + brand);

        System.out.println("Model: " + model);

        System.out.println("Year: " + year);

    }

}


public class Main {

    public static void main(String[] args) {

        // Creating objects using constructors

        Car car1 = new Car("Toyota", "Camry", 2020);

        Car car2 = new Car("Honda", "Accord", 2019);


        // Displaying car information

        System.out.println("Car 1:");

        car1.displayInfo();


        System.out.println("\nCar 2:");

        car2.displayInfo();

    }

}



In this program:


- We have a class `Car` with three instance variables: `brand`, `model`, and `year`.

- We define a constructor `Car()` which takes three parameters (`brand`, `model`, and `year`) and initializes the instance variables.

- We also have a method `displayInfo()` to display the information of the car.

- In the `Main` class, we create two `Car` objects using the constructor with parameters, passing the specific values for each car.

- We then call the `displayInfo()` method on each `Car` object to print out their information.

Post a Comment

Previous Post Next Post