Mutable and Immutable Objects Revisited
with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
public
or private
final
or notfinal
public
or
private
(depending on the methods
included in the class)final
or
private
(or both)public class Point { public double x, y; }
public class Point { public final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } }
public class Point { private double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } }
public class Point { private double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } }
public class Rectangle { public double x, y; public double width, height; }
This implementation isn't safe if the width
and the
height
can't be negative.
public class Rectangle { private double x, y; private double width, height; public Rectangle(double x, double y, double width, double height) { setX(x); setY(y); setWidth(width); setHeight(height); } public void setHeight(double height) { if (height < 0) { y = y + height; this.height = -height; } } public void setWidth(double width) { if (width < 0) { x = x + width; this.width = -width; } } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } }
Rectangle
Class
public class Rectangle { public final double[] corner; public final double[] size; public Rectangle(double[] corner, double[] size) { this.corner = corner; this.size = size; } }
Rectangle
Class
double[] c = { 0.0, 0.0}; double[] s = {10.0, 20.0}; Rectangle r; r = new Rectangle(c, s); s[0] = 50.0;
final
?
private
!
Rectangle
Class
public class Rectangle { private final Point corner; private final Point size; public Rectangle(Point corner, Point size) { this.corner = corner; this.size = size; } }
Rectangle
Class
Point c = new Point( 0.0, 0.0); Point s = new Point(10.0, 20.0); Rectangle r = new Rectangle(c, s); s.setX(50.0);
Rectangle
Class
public class Rectangle { private final Point corner; private final Point size; public Rectangle(Point corner, Point size) { this.corner = new Point(corner.getX(), corner.getY()); this.size = new Point(size.getX(), size.getY()); } }