0
0
Javaprogramming~5 mins

Object interaction in Java

Choose your learning style9 modes available
Introduction

Objects work together by calling each other's methods to get things done. This helps break big tasks into smaller, manageable parts.

When one object needs information from another to complete a task.
When you want to organize your program into smaller pieces that talk to each other.
When you want to reuse code by letting objects share behavior.
When modeling real-world things that interact, like a car and its engine.
When you want to keep your code clean and easy to understand.
Syntax
Java
class ClassA {
    void methodA() {
        ClassB b = new ClassB();
        b.methodB();
    }
}

class ClassB {
    void methodB() {
        System.out.println("Hello from ClassB");
    }
}

One object creates or receives a reference to another object to call its methods.

Methods are called using the dot (.) operator.

Examples
A Room object uses its Light object to turn on the light when entering.
Java
class Light {
    void turnOn() {
        System.out.println("Light is on");
    }
}

class Room {
    Light light = new Light();
    void enter() {
        light.turnOn();
    }
}
A Car object tells its Engine object to start before driving.
Java
class Engine {
    void start() {
        System.out.println("Engine started");
    }
}

class Car {
    Engine engine = new Engine();
    void drive() {
        engine.start();
        System.out.println("Car is driving");
    }
}
Sample Program

The User object uses the Printer object to print a message. This shows how objects work together by calling each other's methods.

Java
class Printer {
    void printMessage(String message) {
        System.out.println(message);
    }
}

class User {
    Printer printer = new Printer();
    void sendMessage() {
        printer.printMessage("Hello from User!");
    }
}

public class Main {
    public static void main(String[] args) {
        User user = new User();
        user.sendMessage();
    }
}
OutputSuccess
Important Notes

Objects communicate by calling methods on each other.

Always create or get a reference to the object you want to interact with.

This helps keep code organized and easier to maintain.

Summary

Objects interact by calling each other's methods.

This allows breaking tasks into smaller parts handled by different objects.

Using object interaction makes your program organized and easier to understand.