Visibility in Java
Methods and fields may or may not be accessible in subclasses,
depending on their access modifiers.
- package:
Example: int size;
No modifier means the method or field is accessible only within the
package in which the class is defined.
By default the "package" is the source file containing the class definition.
- public:
Example: public int size;
The method or field can be accessed from everywhere.
- private:
Example: private int size;
The method or field can only be accessed from within the class definition.
This is typically used to prevent other classes from accessing fields
directly. Access is forced to be done through (public) methods.
- protected:
Example: protected int size;
The method or field can be accessed from within the class and all
subclasses, but nowhere else.
Example:
class Rectangle {
private Point origin, corner;
/* make sure origin is left top and
corner of right bottom */
public Rectangle(Point org, Point cor) {
if (org.x <= cor.x)
if (org.y <= cor.y) {
origin = new Point(org.x, org.y);
corner = new Point(cor.x, cor.y);
} else {
origin = new Point(org.x, cor.y);
corner = new Point(cor.x, org.y);
}
else
if (org.y <= cor.y) {
origin = new Point(cor.x, org.y);
corner = new Point(org.x, cor.y);
} else {
origin = new Point(cor.x, cor.y);
corner = new Point(org.x, org.y);
}
}
}