Rule 2: In Public classes, Use Accessors methods IN place of public fields:
In public class use accessor instead of public fields (to class’s internal representation) because public fields not provide encapsulation.
// Degenerate classes like this should not be public! Not ensures encapsulation
class Point {
public double x;
public double y;
}
// Encapsulation of data by accessor methods and mutators
class Point {
private double x;
private double 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; }
}
Usage of public fields in public class, leads to following drawback
- All related drawbacks of exposed data (thread unsafe etc.)
Note: mutators (setters) should be used with mutable objects only
Broader view on accessibility of public fields- While it’s never a good idea for a public class to expose fields directly, it is less harmful if the fields are immutable. You can’t change the representation of
such a class without changing its API,