Simple Object Creation and Method Invocation Example

// Define a class named Car
class Car {
    // Attributes of the Car class
    String make;
    String model;
    int year;

    // Constructor for initializing Car objects
    Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Method to display car details
    void displayDetails() {
        System.out.println("Car Make: " + make);
        System.out.println("Car Model: " + model);
        System.out.println("Car Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Car object using the constructor
        Car myCar = new Car("Toyota", "Corolla", 2020);

        // Call the method to display car details
        myCar.displayDetails();
    }
}

Main.main(null);

Object Interaction and Passing Objects as Arguments Example

// Define a class named Rectangle
class Rectangle {
    // Attributes of the Rectangle class
    double length;
    double width;

    // Constructor to initialize Rectangle objects
    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Method to calculate the area of the rectangle
    double calculateArea() {
        return length * width;
    }
}

// Define a class named AreaCalculator
class AreaCalculator {
    // Method to calculate and display the area of a Rectangle object
    void printArea(Rectangle rect) {
        double area = rect.calculateArea();
        System.out.println("Area of the rectangle: " + area);
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Rectangle object
        Rectangle myRectangle = new Rectangle(5.0, 3.5);

        // Create an AreaCalculator object
        AreaCalculator calculator = new AreaCalculator();

        // Pass the Rectangle object to the printArea method
        calculator.printArea(myRectangle);
    }
}

Main.main(null);