Modelo

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

Creating a New Object in Java

Oct 15, 2024

To create a new object in Java, you need to use the 'new' keyword followed by the constructor of the class. Here's an example:

Class Car {

String model;

int year;

public Car(String modelName, int manufactureYear) {

model = modelName;

year = manufactureYear;

}

}

In the example above, we have a class 'Car' with two attributes: 'model' and 'year'. The constructor takes two parameters and assigns the values to the attributes. Now, to create a new Car object, you can use the following code:

Car myCar = new Car('Toyota', 2020);

This line of code creates a new instance of the Car class and assigns it to the variable 'myCar'. You can then access the attributes of the object using dot notation:

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

System.out.println(myCar.year); // Output: 2020

That's how you create a new object in Java! Remember to use the 'new' keyword and the constructor of the class to instantiate a new object.

Recommend