Forums Register Login

Unable to figure for storing var in the memory

+Pie Number of slices to send: Send
I confuse in this issue. Basically I set my color=Red to Class b. Then from class c (Note: I do not want to call from class a directly), I retrieved my color but I got the default color=Blue instead of Red. Any ideas?
Greatly appreciated!
Thank you for helping me anyone!

--------------Class a----------------------
public class a {
public static void main (String str[]) {
bb.setColor("red");
c cc = new c();

System.out.println("My get Color" + cc.get());

}
}
--------------Class b--------------------------
public class b {
public String colorName = "blue";
public void setColor(String b){
colorName = b;
}
public String getColor() {
return colorName;
}
}
--------------Class c----------------------------
public class c {
public String get() {

return new b().getColor();

}
}
+Pie Number of slices to send: Send
hi Frank
at line - bb.setColor("red");
the color indeed gets changed to "red" BUT that is in "bb" object reference.
now, at line - return new b().getColor(); line, u r doing new b() which means u created a new object reference of class b right? this creates a "new" object of class b and there the variable colorName is still "blue" because u never called setColor() on that object.
if u do,
b tempB = new b();
tempB.setColor("red");
return tempB.getColor() instead then it would work...
u see my point?
regards
maulin
+Pie Number of slices to send: Send
Thank you Maulin! Good point!
Always! Wait. Never. Shut up. Look at this tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 534 times.
Similar Threads
Question on Garbage Collection
Static methods - the norm?
Customize Sortling
Using Method Invocations
initialization
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:44:09.