Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

Creating a New Object in Java - Example

Oct 18, 2024

In Java, you can create new objects using the 'new' keyword followed by the constructor of the class. Let's take an example to understand how this works.

Suppose we have a class called 'Car' with the following attributes and constructor:

```java

public class Car {

String make;

String model;

public Car(String make, String model) {

this.make = make;

this.model = model;

}

}

```

Now, to create a new object of the 'Car' class, we can use the following code:

```java

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

```

In this example, we are creating a new object called 'myCar' of the 'Car' class. We are passing the values 'Toyota' and 'Corolla' to the constructor, which initializes the 'make' and 'model' attributes of the object.

Once the object is created, we can access its attributes and methods using the dot (.) operator. For example:

```java

System.out.println(myCar.make); // Output: Toyota

System.out.println(myCar.model); // Output: Corolla

```

It's important to note that when you create a new object in Java, memory is allocated for the object on the heap. The constructor is called to initialize the object, and a reference to the object is returned, which can be stored in a variable for further use.

In addition to creating objects using the 'new' keyword, you can also create objects using the 'getInstance()' method for singleton classes or using factory methods to create objects based on certain conditions.

In conclusion, creating a new object in Java is a fundamental concept, and understanding how to do it is crucial for any Java developer. By following the example provided and practicing creating objects of different classes, you can gain a better understanding of object creation and manipulation in Java.

Recommend