Sunday, 30 April 2023

What is Constructor in Java? with example.

 




In Java, A Constructor Is A Special Type Of Method That Is Used To Initialize The Object Of A Class. The Constructor Has The Same Name As The Class And Is Used To Create Objects Of The Class. Here's An Example Of A Constructor In Java:


```

public class Car {

    private String make;

    private String model;

    private int year;


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

        this.make = make;

        this.model = model;

        this.year = year;

    }


    // getter and setter methods for the variables

    public String getMake() {

        return make;

    }


    public void setMake(String make) {

        this.make = make;

    }


    public String getModel() {

        return model;

    }


    public void setModel(String model) {

        this.model = model;

    }


    public int getYear() {

        return year;

    }


    public void setYear(int year) {

        this.year = year;

    }

}

```


In This Example, The `Car` Class Has A Constructor That Takes Three Parameters: `Make`, `Model`, And `Year`. When A New Object Of The `Car` Class Is Created Using This Constructor, The Values Of `Make`, `Model`, And `Year` Are Assigned To The Corresponding Instance Variables Of The Object.


For Example, To Create A New Object Of The `Car` Class, You Can Use The Following Code:


```

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

```


This code creates a new object of the `Car` class with the make "Toyota", model "Camry", and year 2022. The constructor initializes the instance variables of the object with these values.


Constructors Are Useful For Initializing The Variables Of An Object And Ensuring That The Object Is In A Valid State When It Is Created. In Java, If A Class Does Not Define A Constructor, A Default Constructor Is Automatically Created By The Compiler. However, If You Need To Perform Additional Initialization Or Validation Of The Object, You Can Define Your Own Constructor As Shown In The Example Above.

No comments:

Post a Comment

What is Java Permutation and Combination Program?

Here's A Java Program That Calculates Permutations And Combinations: ```Java Import Java.Util.Scanner; Public Class Permutationcombinati...