Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Java : Assume object reference or make copy
- public class Point {
- public int x;
- public int y;
- public Point(int xVal, int yVal) {
- x = xVal;
- y = yVal;
- }
- public Point(Point pt) {
- x = pt.x;
- y = pt.y;
- }
- }
- public class BoundingBox {
- public Point topLeft;
- public Point bottomRight;
- public BoundingBox(Point setTopLeft, Point setBottomRight) {
- topLeft = new Point(setTopLeft);
- bottomRight = new Point(setBottomRight);
- }
- }
- Point topLeft = new Point(1, 2);
- Point bottomRight = new Point(3, 4);
- BoundingBox box = new BoundingBox(topLeft, bottomRight);
- topLeft.x = 5; // Oops, this just changed box.topLeft.x
- public class Point {
- public final int x;
- public final int y;
- public Point(int xVal, int yVal) {
- x = xVal;
- y = yVal;
- }
- public Point(Point pt) {
- x = pt.x;
- y = pt.y;
- }
- }
- public class MyClass {
- private Point foo;
- private Point bar;
- public MyClass(Point foo, Point bar) {
- this.foo = foo;
- this.bar = bar;
- }
- public Point foo() {
- return foo;
- }
- public Point bar() {
- return bar;
- }
- . . .
- //Seems harmless enough?
- //Lets destroy it
- Point foo = new Point(1 ,2);
- Point bar = new Point(3 ,4);
- MyClass mc = new MyClass(foo, bar);
- bar.x = 99; //<-- changes internal of mc!
- //Fixed version!
- public MyClass(Point foo, Point bar) {
- this.foo = new Point(foo.getLocation());
- this.bar = new Point(bar.getLocation());
- }
- public Point foo() {
- return new Point(foo.getLocation());
- }
- public Point bar() {
- return new Point(bar.getLocation());
- }
- . . .
Add Comment
Please, Sign In to add comment