How to Create an Object in Java
In Java, creating an object involves three main steps: declaring a variable of the class type,
instantiating the object using the new keyword, and initializing the object by calling a constructor.
Here's a step-by-step explanation:
1. Declare a variable of the class type:
This step involves specifying the class of the object you want to create and declaring a variable of
that class type.
```java
ClassName objectName;
```
For example:
```java
Car myCar;
```
2. Instantiate the object using the `new` keyword:
This step involves using the `new` keyword to create an instance of the class. The `new` keyword
allocates memory for the object.
```java
objectName = new ClassName();
```
For example:
```java
myCar = new Car();
```
3. Initialize the object by calling a constructor:
A constructor is a special method in the class that is called when an object is created. The
constructor initializes the object. If no constructor is explicitly defined, Java provides a default
constructor.
Putting it all together:
```java
ClassName objectName = new ClassName();
```
For example:
```java
Car myCar = new Car();
```
Complete Example:
Consider a `Car` class with a simple constructor:
```java
public class Car {
String color;
String model;
// Constructor
public Car(String color, String model) {
this.color = color;
this.model = model;
// Method to display car details
public void display() {
System.out.println("Color: " + color);
System.out.println("Model: " + model);
```
To create an object of the `Car` class and initialize it, you can do the following:
```java
public class Main {
public static void main(String[] args) {
// Create an object of Car class
Car myCar = new Car("Red", "Toyota");
// Call a method on the object
myCar.display();
```
Explanation:
- `Car myCar;` declares a variable `myCar` of type `Car`.
- `myCar = new Car("Red", "Toyota");` creates a new `Car` object with the specified color and
model, and assigns it to the variable `myCar`.
- `myCar.display();` calls the `display` method on the `myCar` object, which prints the car's details.
This is how you create and use objects in Java.