How do you create an object in Java?

In Java, objects are created by using the new keyword along with the class constructor. Here's the basic process:

Steps to Create an Object:

  1. Define a Class: A class acts as a blueprint for objects.
  2. Instantiate the Object: Use the new keyword followed by the constructor of the class to create an instance of the class (an object).
  3. Assign to a Reference Variable: Store the object in a reference variable of the appropriate class type.

Syntax:

ClassName objectReference = new ClassName();

Example:

class Car {
    String model;
    int year;

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

// Method to display details
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}


}

public class Main {

public static void main(String args) {

// Creating an object of the Car class

Car myCar = new Car("Tesla Model 3", 2023);

// Accessing object's method
myCar.displayInfo();

}


}