Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in Java

Does the private members in Java differs from other programming language private members? Because I was surprised that I could just pass an Object of some type to compareTo, and then access the private members of that Object without using any getMethod.

E.g.

public class Foo implements Comparable<Foo>{

    private int bar;

    public Foo() { bar = 1; }

    public int compareTo(Foo o) {
        if(bar == o.bar)
            return 0;
        return 1;
    }
}
like image 402
starcorn Avatar asked Dec 07 '22 21:12

starcorn


2 Answers

Yes, private members in Java differ from some other languages. For example, I don't think the equivalent code in C++ would be valid.

On the other hand, it would be valid in C#. There are still some differences between C# and Java in terms of access to private members from enclosing or nested classes, but they're basically similar.

You shouldn't really expect any two languages to have identical behaviour. It's worth consulting the specification of the language you're actually interested in - in this case, it's section 6.6 of the JLS.

like image 146
Jon Skeet Avatar answered Dec 10 '22 12:12

Jon Skeet


Even though I progam Java for a living for 11 years, I was freaked out when I discovered this fact two (!) years ago. I must have read it before, but somehow it never sunk in. I agree that this seems weird at first, but when you think about it a bit longer it makes perfect sense.

What is OO all about? About separation of concerns and information hiding, right? So in your design you always (should) try to avoid having to 'know' about things outside of your own concern, because this equals making assumptions; the things you 'know' at design time might change later on and invalidate the assumption your class is making.

In this case, you are allowing Foo to access another Foo's private bar, which at first feels like 'knowing' about something outside of Foo's concern. But because we are talking about two instances of the exact same class (Foo) this is actually not outside of our concern! If for example we change bar from int to double, we are doing so within the same class, and any compile errors will show up immediately.

Also, imagine that this type of access were prohibited. So what if Foo called its own compareTo, passing 'this' as an argument? Then we would have to forbid a Foo to access it's own private bar? And what about private static fields? That would be very confusing, don't you agree?

A bit long-winded maybe, but I hope you can appreciate that after the first shock, this actually makes sense! (-:

like image 45
Adriaan Koster Avatar answered Dec 10 '22 12:12

Adriaan Koster