Objects work together by calling each other's methods to get things done. This helps break big tasks into smaller, manageable parts.
Object interaction in Java
Start learning this pattern below
Jump into concepts and practice - no test required
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.
class Light { void turnOn() { System.out.println("Light is on"); } } class Room { Light light = new Light(); void enter() { light.turnOn(); } }
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"); } }
The User object uses the Printer object to print a message. This shows how objects work together by calling each other's methods.
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(); } }
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.
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.
Practice
What does it mean when two objects in Java interact?
Choose the best explanation.
Solution
Step 1: Understand object interaction meaning
Object interaction means objects communicate by calling each other's methods to work together.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.Final Answer:
One object calls a method of another object to perform a task. -> Option AQuick Check:
Object interaction = method calls between objects [OK]
- Thinking objects share memory to interact
- Confusing object creation with interaction
- Assuming variables store multiple objects
Which of the following is the correct syntax to call a method start() on an object car in Java?
Solution
Step 1: Recall Java method call syntax
In Java, to call a method on an object, useobjectName.methodName();.Step 2: Check each option
car.start(); matches correct syntax. Options A, B, and C are invalid Java syntax.Final Answer:
car.start(); -> Option BQuick Check:
Method call = object.method() [OK]
- Using arrow (->) like in C++
- Reversing method and object order
- Calling method like a function with object as argument
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?
Solution
Step 1: Check initial light status
Initially,isOnis false, soroom.lightStatus()prints false.Step 2: Toggle light and check status again
Callingroom.switchLight()togglesisOnto true. Thenroom.lightStatus()prints true.Final Answer:
false true -> Option AQuick Check:
Initial false, toggled true = false then true [OK]
- Assuming toggle sets true first without initial check
- Confusing method calls and variable values
- Ignoring initial value of isOn
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");
}
}Solution
Step 1: Check object declaration and initialization
The object 'printer' is declared but never assigned a new Printer instance.Step 2: Understand consequences of uninitialized object
Calling a method on an uninitialized object causes a NullPointerException at runtime.Final Answer:
The object 'printer' is declared but not initialized before use. -> Option CQuick Check:
Uninitialized object causes runtime error [OK]
- Assuming declaration equals initialization
- Thinking method absence causes error here
- Ignoring runtime NullPointerException
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();
}Solution
Step 1: Understand transfer logic
To transfer money, withdraw from current account and deposit into the other account.Step 2: Check method calls for interaction
Callingwithdraw(amount)on this object anddeposit(amount)on the other object shows interaction.Final Answer:
withdraw(amount); other.deposit(amount); -> Option DQuick Check:
Transfer = withdraw from one, deposit to another [OK]
- Withdrawing from the wrong account
- Directly changing balance without methods
- Depositing before withdrawing
