Guest User

Untitled

a guest
Aug 15th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. Java : Assume object reference or make copy
  2. public class Point {
  3. public int x;
  4. public int y;
  5.  
  6. public Point(int xVal, int yVal) {
  7. x = xVal;
  8. y = yVal;
  9. }
  10.  
  11. public Point(Point pt) {
  12. x = pt.x;
  13. y = pt.y;
  14. }
  15. }
  16.  
  17. public class BoundingBox {
  18. public Point topLeft;
  19. public Point bottomRight;
  20.  
  21. public BoundingBox(Point setTopLeft, Point setBottomRight) {
  22. topLeft = new Point(setTopLeft);
  23. bottomRight = new Point(setBottomRight);
  24. }
  25. }
  26.  
  27. Point topLeft = new Point(1, 2);
  28. Point bottomRight = new Point(3, 4);
  29. BoundingBox box = new BoundingBox(topLeft, bottomRight);
  30.  
  31. topLeft.x = 5; // Oops, this just changed box.topLeft.x
  32.  
  33. public class Point {
  34. public final int x;
  35. public final int y;
  36.  
  37. public Point(int xVal, int yVal) {
  38. x = xVal;
  39. y = yVal;
  40. }
  41.  
  42. public Point(Point pt) {
  43. x = pt.x;
  44. y = pt.y;
  45. }
  46. }
  47.  
  48. public class MyClass {
  49. private Point foo;
  50. private Point bar;
  51.  
  52. public MyClass(Point foo, Point bar) {
  53. this.foo = foo;
  54. this.bar = bar;
  55. }
  56.  
  57. public Point foo() {
  58. return foo;
  59. }
  60.  
  61. public Point bar() {
  62. return bar;
  63. }
  64.  
  65. . . .
  66.  
  67. //Seems harmless enough?
  68. //Lets destroy it
  69. Point foo = new Point(1 ,2);
  70. Point bar = new Point(3 ,4);
  71. MyClass mc = new MyClass(foo, bar);
  72. bar.x = 99; //<-- changes internal of mc!
  73.  
  74. //Fixed version!
  75. public MyClass(Point foo, Point bar) {
  76. this.foo = new Point(foo.getLocation());
  77. this.bar = new Point(bar.getLocation());
  78. }
  79.  
  80. public Point foo() {
  81. return new Point(foo.getLocation());
  82. }
  83.  
  84. public Point bar() {
  85. return new Point(bar.getLocation());
  86. }
  87.  
  88. . . .
Add Comment
Please, Sign In to add comment