Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 628
Devoted Avatar asked Apr 27 '09 05:04

Devoted


2 Answers

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.

like image 88
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


No, private fields can be accessed even from other instances (within a method of the same class).

They cannot be accessed from subclasses, however, not even within the same instance.

You provide getter methods to allow "outside" code to access fields in your class. Since it is up to you what getters you provide, how visible you make them, and how they are implemented, you can exercise a lot of control as to who can access the data and how.

Note that there does not really need to be a name field if there is a getName: it is entirely up to the implementation of the getter where that data comes from.

Even if the getter (or setter) just wraps a private field, it is good style to have these setters and getters (as opposed to allowing direct field access).

like image 30
Thilo Avatar answered Oct 06 '22 00:10

Thilo