Why Java is Not My Favorite Language — Reason #36

Member access modifiers apply that the class level not the object level. For example, the following perfectly legal in Java.

class Foo
    private String name;

    public String someOneElsesName(Foo another)
        return another.name;

The method someOneElsesName() returns the value of a private instance variable of an object that is not one on which the method was executed. This is suppose to promote good encapsulation?

6 thoughts on “Why Java is Not My Favorite Language — Reason #36

  1. That’s sort of a stange piece of code. On an academic level, you have point. But practically speaking, I’ve never encountered an instance where this wouild have mattered. And even academially speaking, I’m not sure this is really a gross violation of encapsulation. Basically it says, code in a class is written to operate on code in a class. No internals have been revealed to code outside the class.

  2. I think the reason this bothers me is that I think encapsulation should object based but in Java the encapsulation is class based. This difference explains why Java’s private access modifier excludes subclasses, because they are different classes.

  3. I used to agree with you. However, this is actually a very useful modification to encapsulation. I have saved many lines of code and written much cleaner code on account of class-level encapsulation.

Comments are closed.