Question 12
Back to Exercise
What is the output of the following Java program?
class Address {
String city;
Address(String c) { city = c; }
Address(Address o) { this(o.city); }
}
class Customer {
private final Address address;
Customer(Address a) { address = new Address(a); }
Address getAddress() { return new Address(address); }
void moveTo(String city) { address.city = city; }
}
public class Main {
public static void main(String[] args) {
Address a = new Address("Pune");
Customer c = new Customer(a);
a.city = "Delhi";
c.getAddress().city = "Goa";
String before = c.getAddress().city;
c.moveTo("Mumbai");
System.out.println(before + " " + c.getAddress().city + " " + a.city);
}
}
- A Pune Mumbai Delhi Correct
- B Goa Mumbai Delhi
- C Delhi Mumbai Delhi
- D Pune Pune Delhi
Correct Answer: Option A
Copies in the constructor and the getter mean only moveTo can change the customer's address.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!