繁体   English   中英

为什么受保护的属性和私有属性可以由同一个类而不是同一个对象访问?

[英]Why protected and private attributes are accessible by same class rather than by the same object?

例如,我们有类Man

如果Man.age受到保护,那么我不明白为什么chuckNorris (类Man实例)可以更改对象jackBauer (类Man另一个实例)的protected / private属性age 他不应该这样做(IMO)。

在我的脑海里,一个保护/私有属性的应该是只属于对象本身,而不是 ...

我想要一些解释,我很困惑。

马蒂厄是对的。 cuckNorris可以做jackBauer.age

但是没有问题。 如果您在Man中引用Man实例属性,那意味着您正在编写Man类,因此您知道自己在做什么。

问题是如果你传给我Man类,我可以访问Man属性而不知道Man类是如何编码的。

Setter和getter可能正在做一些我不知道的业务逻辑,我不需要知道。 但编码Mam的人确实知道。

考虑这个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的protected或private变量

如果你愿意,你可以允许它,

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参数标记为不可更改,但不是Java中 - 我认为这不是什么大问题。

[*}你可以通过将Base所有字段标记为final,尽管在构造对象之后甚至实例本身都不能更改成员。

私有属性只能通过类中的方法访问。 受保护的属性仅在后代类中是accessibe。 因此,对象jackbauer不能修改私人或受保护的对象chuckNorris类Man。 希望这会有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM