Programming Tutorials

Creating Objects in Java

By: aathishankaran in Java Tutorials on 2007-03-21  

In Java, objects can be created using the new operator followed by a call to the constructor of the class. Here is an example:

public class Car {
    String make;
    String model;
    int year;

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public void start() {
        System.out.println("Starting the " + year + " " + make + " " + model);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", "Camry", 2021);
        myCar.start();
    }
}

In this example, we define a class Car with three properties make, model, and year. We also define a constructor that takes three arguments and initializes the properties. We also define a method start() that prints a message to the console.

In the Main class, we create a new Car object using the constructor and passing in the arguments "Toyota", "Camry", and 2021. We store this object in the variable myCar. We then call the start() method on myCar, which prints the message "Starting the 2021 Toyota Camry" to the console.

This is just one example of how to create objects in Java. The syntax may vary depending on the specific requirements of the class being instantiated.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)