Hi all,
I would have a question.

I know that I should (or must) respect the encapsulation rule (as one of the main three Java features) but what about if I have some "Data Structure"? I mean something like "struct" in C/C++.
So if my class contains only data (not methods), is it "appropriate" to make that data (variables) public?


class Point
    // Fields
    public int x;
    public int y;

    // Constructor
    public Point(int x, int y)
        this.x = x;
        this.y = y;


It is always okay to expose public fields when the purpose of a class is to contain said field. For a tiny private data struct? Okay. For a public use-everywhere data structure? Okay. For example, it's okay for a binary tree datatype (not a binary search tree, just a plain old binary tree) to expose its fields publicly.

The question is whether you might want to switch to an implementation that is different but somehow has equal behavior. That's possible if your notion of what a datatype is depends on facts such as the way it behaves, but doesn't depend on internal implementation. On the other hand, if the notion of what your datatype is depends solely on what it contains, or partly so, then your fields or some of your fields should be publicly exposed. For example, the notion of a DateTime does not depend on what it contains, so there's no reason you'd want to expose your internal implementation. On the other hand, the notion of a point in a plane is that it's a pair of real numbers.

Josh Bloch's example should be regarded as a parody of his opinion. His mention of the Dimension class was a byproduct of the fact that the fields were mutable, not the fact that they were publicly exposed, as he claims.