Why are protected and private attributes accessible to the same class, and not to the same object?

For example, we have a class Man

If it Man.ageis protected, then I don’t understand why chuckNorris(the class instance Man) can change the protected / private attribute of the ageobject jackBauer(another class instance Man). He should not do this (IMO).

In my opinion, the meaning the protected / private attribute should belong only to the object itself , and not to the class...

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

+3
source share
3 answers

Mattiu is right. cuckNorris can do jackBauer.age

. Man Man, , Man, , .

, Man, Man, , Man.

-, , . , , .

+1

Java:

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);

( , ) foo bar

, ,

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);

changeB other [*], , . other unchangable, Java - .

[*} , Base , , .

+1

. accessibe . jackbauer chuckNorris Man. ,

0

Source: https://habr.com/ru/post/1768479/


All Articles