Bird
Raised Fist0
Javaprogramming~10 mins

Object interaction in Java - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Object interaction
Create Object A
Create Object B
Object A calls method on Object B
Object B executes method
Return result to Object A
Object A uses result
This flow shows how one object creates another, calls its method, and uses the returned result.
Execution Sample
Java
class Printer {
  void printMessage(String msg) {
    System.out.println(msg);
  }
}

class User {
  void sendPrint(Printer p) {
    p.printMessage("Hello from User");
  }
}

public class Main {
  public static void main(String[] args) {
    Printer printer = new Printer();
    User user = new User();
    user.sendPrint(printer);
  }
}
User object calls a method on Printer object to print a message.
Execution Table
StepActionObjectMethod CalledParameterOutput
1Create Printer objectPrinterN/AN/APrinter instance created
2Create User objectUserN/AN/AUser instance created
3User calls sendPrintUsersendPrintPrinter objectNo output
4sendPrint calls printMessagePrinterprintMessage"Hello from User"Prints: Hello from User
5printMessage completesPrinterprintMessageN/AMethod returns void
6sendPrint completesUsersendPrintN/AMethod returns void
7main completesMainmainN/AProgram ends
💡 Program ends after main method completes
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
printernullPrinter instancePrinter instancePrinter instancePrinter instance
usernullnullUser instanceUser instanceUser instance
Key Moments - 3 Insights
Why does User need a Printer object to call printMessage?
Because printMessage belongs to Printer, User must have a reference to Printer to call its method, as shown in step 3 of the execution_table.
Does printMessage return any value to sendPrint?
No, printMessage returns void (no value), so sendPrint just calls it and continues, as seen in steps 4 and 5.
What happens if User tries to call printMessage without a Printer object?
It causes an error because printMessage is not in User; User must have a Printer reference to call it, shown by the need for parameter in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when printMessage is called?
ANo output
BPrints: Hello from User
CReturns a string
DThrows an error
💡 Hint
Check step 4 in the execution_table where printMessage prints the message.
At which step does the User object call a method on the Printer object?
AStep 2
BStep 5
CStep 3
DStep 7
💡 Hint
Look at step 3 in the execution_table where sendPrint is called with Printer as parameter.
If the Printer object was not created, what would happen at step 3?
ANullPointerException error occurs
BsendPrint calls printMessage anyway
CUser calls sendPrint successfully
DProgram prints a default message
💡 Hint
Refer to variable_tracker and step 3 in execution_table; without Printer instance, calling method causes error.
Concept Snapshot
Object interaction in Java:
- One object holds reference to another
- Calls methods on that object using dot notation
- Methods can return values or be void
- Objects must be created before interaction
- Example: user.sendPrint(printer) calls printer.printMessage()
Full Transcript
This example shows how two objects interact in Java. First, a Printer object is created, then a User object. The User object calls its sendPrint method, passing the Printer object. Inside sendPrint, the Printer's printMessage method is called with a message. The message is printed to the console. The methods return void, so no values are passed back. The program ends after main completes. This demonstrates how objects communicate by calling each other's methods using references.

Practice

(1/5)
1.

What does it mean when two objects in Java interact?

Choose the best explanation.

easy
A. One object calls a method of another object to perform a task.
B. Two objects share the same memory location.
C. Objects are created using the same class.
D. Objects are stored in the same variable.

Solution

  1. Step 1: Understand object interaction meaning

    Object interaction means objects communicate by calling each other's methods to work together.
  2. Step 2: Evaluate options

    Only One object calls a method of another object to perform a task. describes calling methods between objects, which is how interaction happens.
  3. Final Answer:

    One object calls a method of another object to perform a task. -> Option A
  4. Quick Check:

    Object interaction = method calls between objects [OK]
Hint: Objects interact by calling methods on each other [OK]
Common Mistakes:
  • Thinking objects share memory to interact
  • Confusing object creation with interaction
  • Assuming variables store multiple objects
2.

Which of the following is the correct syntax to call a method start() on an object car in Java?

easy
A. start(car);
B. car.start();
C. car->start();
D. start.car();

Solution

  1. Step 1: Recall Java method call syntax

    In Java, to call a method on an object, use objectName.methodName();.
  2. Step 2: Check each option

    car.start(); matches correct syntax. Options A, B, and C are invalid Java syntax.
  3. Final Answer:

    car.start(); -> Option B
  4. Quick Check:

    Method call = object.method() [OK]
Hint: Use objectName.methodName() to call methods [OK]
Common Mistakes:
  • Using arrow (->) like in C++
  • Reversing method and object order
  • Calling method like a function with object as argument
3.

Consider the following Java code:

class Light {
    boolean isOn = false;
    void toggle() {
        isOn = !isOn;
    }
    boolean status() {
        return isOn;
    }
}

class Room {
    Light light = new Light();
    void switchLight() {
        light.toggle();
    }
    boolean lightStatus() {
        return light.status();
    }
}

public class Main {
    public static void main(String[] args) {
        Room room = new Room();
        System.out.println(room.lightStatus());
        room.switchLight();
        System.out.println(room.lightStatus());
    }
}

What is the output when this program runs?

medium
A. false true
B. true false
C. false false
D. true true

Solution

  1. Step 1: Check initial light status

    Initially, isOn is false, so room.lightStatus() prints false.
  2. Step 2: Toggle light and check status again

    Calling room.switchLight() toggles isOn to true. Then room.lightStatus() prints true.
  3. Final Answer:

    false true -> Option A
  4. Quick Check:

    Initial false, toggled true = false then true [OK]
Hint: Track boolean changes step-by-step [OK]
Common Mistakes:
  • Assuming toggle sets true first without initial check
  • Confusing method calls and variable values
  • Ignoring initial value of isOn
4.

Find the error in this Java code snippet involving object interaction:

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

public class Main {
    public static void main(String[] args) {
        Printer printer;
        printer.print("Hello World");
    }
}
medium
A. The print statement syntax is incorrect.
B. The method 'print' is not defined in the Printer class.
C. The object 'printer' is declared but not initialized before use.
D. The class Printer should be public.

Solution

  1. Step 1: Check object declaration and initialization

    The object 'printer' is declared but never assigned a new Printer instance.
  2. Step 2: Understand consequences of uninitialized object

    Calling a method on an uninitialized object causes a NullPointerException at runtime.
  3. Final Answer:

    The object 'printer' is declared but not initialized before use. -> Option C
  4. Quick Check:

    Uninitialized object causes runtime error [OK]
Hint: Always initialize objects before calling methods [OK]
Common Mistakes:
  • Assuming declaration equals initialization
  • Thinking method absence causes error here
  • Ignoring runtime NullPointerException
5.

You have two classes, BankAccount and Customer. A Customer has a BankAccount object. You want to add a method transferTo in BankAccount that transfers money to another BankAccount. Which of the following best shows how objects interact to perform this transfer?

class BankAccount {
    double balance;
    void deposit(double amount) { balance += amount; }
    void withdraw(double amount) { balance -= amount; }
    void transferTo(BankAccount other, double amount) {
        // Fill in this method
    }
}

class Customer {
    BankAccount account = new BankAccount();
}
hard
A. deposit(amount); withdraw(amount);
B. other.withdraw(amount); deposit(amount);
C. balance -= amount; other.balance += amount;
D. withdraw(amount); other.deposit(amount);

Solution

  1. Step 1: Understand transfer logic

    To transfer money, withdraw from current account and deposit into the other account.
  2. Step 2: Check method calls for interaction

    Calling withdraw(amount) on this object and deposit(amount) on the other object shows interaction.
  3. Final Answer:

    withdraw(amount); other.deposit(amount); -> Option D
  4. Quick Check:

    Transfer = withdraw from one, deposit to another [OK]
Hint: Transfer = withdraw from self, deposit to other [OK]
Common Mistakes:
  • Withdrawing from the wrong account
  • Directly changing balance without methods
  • Depositing before withdrawing