Let's say for instance that we have a class Board
with many fields (ie a rather complex class). We instantiate a Board like so:
Board b = new Board();
Note that for the sake of this example, I am not entering any parameters into the constructor, though in a real example, those may be necessary. If we were to then instantiate a new instance of Board and set it equal to be like so:
Board c = b;
This would not actually create a new board. From what I know, c
and b
now point to the same area of memory, the same Board object. So, if I were to change something about b
, say be incrementing an integer field, like so:
b.count++;//Assume count is an integer field in the Board class.
The value c.count
should be incremented as well. However, when I do this myself, it doesn't work. b.count
is incremented, yet c.count
is not.
Can anyone explain to me why this happens? This effect is something I want to have happen, thus any advice on how to implement this would be very helpful (General examples are fine).
Wrong again:
package cruft;
/**
* Board description here
* @author Michael
* @link
* @since 11/26/12 6:46 PM
*/
public class Board {
public int count;
public static void main(String[] args) {
Board b = new Board();
Board c = b;
System.out.println("b before: " + b);
System.out.println("c before: " + c);
++b.count;
System.out.println("b after : " + b);
System.out.println("c after : " + c);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Board");
sb.append("{count=").append(count);
sb.append('}');
return sb.toString();
}
}
This shouldn't happen. Take a look at this example.
public class Board {
public Integer count = 0;
public static void main(String[] args)
{
Board b = new Board();
Board c = b;
c.count++;
System.out.println("b.count="+b.count);
System.out.println("c.count="+c.count);
}
}
This does not happen in a single thread. if you do that c= b for a second thread, normal visibility rules apply.
First of all, you should try to avoid using public
fields in your objects. Use a private
field, then use a getFieldName()
and a setFieldName(FieldType arg)
method. That way you have more control over what happens, and you can add code if you want other things to happen when a certain variable changes.
That being said, you must have a bug in your code, because:
public static void main(String[] args) {
Board b = new Board();
Board c = b;
System.out.println("BEFORE++: b.count = " + b.count);
System.out.println("BEFORE++: c.count = " + c.count);
b.count++;
System.out.println("AFTER++: b.count = " + b.count);
System.out.println("AFTER++: c.count = " + c.count);
}
public static class Board {
public int count = 0;
}
Outputs:
BEFORE++: b.count = 0
BEFORE++: c.count = 0
AFTER++: b.count = 1
AFTER++: c.count = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.