What is the result of the following program?
Consider the following code fragment
Rectangle r1 = new Rectangle();
r1.setColor(Color.red);
Rectangle r2 = r1;
r2.setColor(Color.blue);
After the above piece of code is executed, what are the colors of r1 and r2 (in this order)?
Code
public class MyClass {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.setColor(Color.RED);
Rectangle r2 = r1;
r2.setColor(Color.BLUE);
System.out.println(r1.getColor());
System.out.println(r2.getColor());
}
static enum Color {
RED, BLUE
}
static class Rectangle {
private Color color;
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return this.color;
}
}
}
Output:
BLUE
BLUE
Comments
Leave a comment