Search code examples
javaencapsulationconceptual

Do objects encapsulate data so that not even other instances of the same class can access the data?


In Java,

Do objects encapsulate data so that not even other instances of the same class can access the data? Only when the keyword "private" is used? What are "accessor methods" in Java - methods like getName()?

Thanks


Solution

  • I don't tend to think of it in terms of one object having access to another, but rather what code has access to what data within an object.

    In Java (and C#, btw) code within a class has access to the private members of any object of the same class. Then you've got package/assembly access and public access.

    The tricky one is protected access, which is sort of access to code in subclasses - but it depends on the target object: you're only allowed to access protected members of an object if it's an instance of the same type as the location of the code, or some subclass - even if it's being exposed by a parent class. So for instance, suppose you had:

    class Parent
    {
        protected int x;
    }
    
    class Child1 extends Parent
    class Child2 extends Parent
    class Grandchild extends Child1
    

    Then within the Child1 code, you can access Parent.x only for objects which are known (at compile-time) to be instances of Child1 or Grandchild. You couldn't, for instance, use new Parent().x or new Child2().x.