Java Class Instantiation Example

The following Java code demonstrates how to instantiate objects from a class.


// Step 1: Define a Class
class Car {
    // Attributes (fields)
    String brand;
    int year;

    // Step 2: Create a Constructor
    Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    // Method to display car info
    void displayCarInfo() {
        System.out.println("Brand: " + brand + ", Year: " + year);
    }
}

// Step 3 & 4: Instantiate an Object in Main Method
public class Main {
    public static void main(String[] args) {
        // Using 'new' keyword to create an object of Car class
        Car myCar = new Car("Toyota", 2022);
        
        // Calling method on the object
        myCar.displayCarInfo();
    }
}