One of my professor has given us a few practice questions for an exam, and one of the questions is something like the below (psuedocode):
a.setColor(blue);
b.setColor(red);
a = b;
b.setColor(purple);
b = a;
//what color is a, and what color is b?
It seems extremely rudimentary to me, so I've proposed the answer that a is 'red', and b is 'red', but I've been told this is incorrect. I've broken down my answer as I would a math problem:
a = 15;
b = 12;
a = b; //a becomes 12
b = 13;
b = a; //b becomes 12
But my thought process is through the mind of C, not Java. I figured there was some universal method for both, but perhaps I am wrong? Is my answer wrong or my professor is wrong? I'm very new to Java, although I have some command of C, Python, and web logic (PHP, Ruby), so I apologize if this is something trivial (which it is).
A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Assuming you've already created two objects, and made variables a
and b
refer to them, you've initially got something like this.
a --> [ white ] b --> [ white ]
Your first two lines change the colours of the objects, to give you
a --> [ blue ] b --> [ red ]
Then, you point the variable a
to the object referred to by b
, so that they both refer to the same object. You now have
[ blue ] b --> [ red ] <-- a
Then you change the colour of the object referred to by b
.
[ blue ] b --> [ purple ] <-- a
Lastly, the line b=a;
does nothing, because b
already refers to the same object as a
.
It's because the fact that in first example, a
and b
are objects so this is what happens in each of the steps:
a <-- is an object
b <-- is an object
a.setColor(blue); <--
a
becomes blueb.setColor(red); <--
b
becomes reda = b; <-- IMPORTANT:: original
a
object is released and available for garbage collection and nowa
holds the reference ofb
object, which meana
andb
are referring the same object now, which isb
.b.setColor(purple); <-- b is purple now. Since a points to b only, a is also purple
Answer: Both a
and b
are purple at this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With