views:

53

answers:

2

For example, we have the class Man

If Man.age is protected, then I don't see why chuckNorris (instance of class Man) can change the protected/private attribute age of the object jackBauer (another instance of class Man). He shouldn't be able to do that (IMO).

In my mind, the value of a protected/private attribute is supposed to belong only to the object itself, not the class...

I need some explanation I think, I'm confused.

+1  A: 

A private attribute is accessible only by method in the class. A protected attribute is accessibe in descendant class only. Therefore an object jackbauer can't modify anything private or protected in an object chuckNorris of class Man. Hope this would help

enokd
You say "A private attribute is accessible only by method in the class", then if jackBauer and chuckNorris are both object of the class Man, then they can share private attributes ??
Matthieu
In this case, it will be a class attribute which is shared by all objects of the class. These attributes are designed by the word static.
enokd
No I'm not talking of static attributes, in saying inside the object chuckNorris I can do : jackBauer.age. And I think this is weird because this is a private attributes, so other objects shouldn't be able to read of modify it. Am I wrong ?
Matthieu
Could you give me a code example? You cannot do that unless you had a public setter function for age.
enokd
+1  A: 

Consider this Java class:

public class Base {
  private int a
  protected int b;

  public Base(int a,int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() {
     return a;
  }

  public int getB() {
    return b;
  } 
}

...
 Base foo = new Base(1,2);
 Base bar = new Base(3,4);

There is no way(maybe except via dirty reflection) the foo instance can change the protected or private variable in bar

You might allow it to if you want,

public class Base {
  private int a
  protected int b;

  public Base(int a,int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() {
     return a;
  }

  public int getB() {
    return b;
  } 
 public void changeB(int newB,Base other) {
   other.b = newB;
 }
}
... 
Base foo = new Base(1,2);
Base bar = new Base(3,4);
foo.changeB(5,bar);

You can't protect the changeB method from altering stuff inside the other object [*], you just have to be careful about what your program does. With some languages you could have marked the other argument as unchangable , but not in Java - I don't find it a big deal.

[*} You could, by marking all the fields of Base as final, though then not even the instance itself could change the members after the object has been constructed.

nos
Ok thanks that's clear. And I think this is just weird that foo can change bar.b even though b is private. I mean private should be related to the instance, not the class.
Matthieu