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?

Example:

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

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

Thanks.

Recommended Answers

All 2 Replies

It really just depends on where and how that class is used. For a tiny private data struct? I'd leave em public. For something that will be used by others, probably best to add accessors.

You can read Josh Bloch's thoughts on the matter here if you're inclined: http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA71&lpg=PA71&dq=java+public+fields+on+small+data+classes+bloch&source=bl&ots=yXFkJkt1OX&sig=PzH5Fo9XfOcs4P2AZScOHjji-bw

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.