Java私有字段可见性 [英] Java Private Field Visibility

查看:203
本文介绍了Java私有字段可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我前几天正在创建一个类,当我意识到它生成了以下工作代码时,使用Eclipse的方法创建了equals方法:

So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following working code:

class Test {
  private int privateInt;
  [...]
  public boolean equals(Object obj) {
    [...]
    Test t = (Test) obj;
    if ( t.privateInt == privateInt ) {
    [...]
  }
}

t.privateInt .. ????它假设是私人的!所以我想除了私有,受保护,包受保护和公开之外还有一个字段可见性。

t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.

那么这里发生了什么?怎么称呼? 有人会在哪里使用它?这不会破坏封装吗?如果班级没有改变者并且我改变了这个怎么办?这也发生在C ++上吗?这是一个OO成语吗?如果没有,那么为什么Java会这样做?

So what is happening here? How is this called? Where would somebody use this? Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?

一般来说,我在哪里可以找到相关的信息?

Generally, where can I find information about this?

谢谢。

推荐答案

可以从同一个班级的不同实例访问。

It's accessible from different instances of the same class.

根据此页(加粗矿井) :


在会员级别,您也可以使用public修饰符或不使用修饰符(package-private),就像使用顶级类一样,并具有相同的含义。对于成员,还有两个额外的访问修饰符:private和protected。 私有修饰符指定只能在自己的类中访问该成员。

为清楚起见,我' ll重写这一行:

For clarity I'll rewrite this line:

if ( t.privateInt == this.privateInt )

我们可以同意允许this.privateInt:您正在类Test的实例中访问它,消息equals具有已被发送到。

We can agree that "this.privateInt" should be allowed: you are accessing it from within the instance of class Test that the message "equals" has been sent to.

t.privateInt应该是可见的不太清楚,因为t是类Test的一个单独实例,我们没有在其equals方法中执行。但是java允许这样做,因为两个对象(t和this)属于同一类Test,并且可以看到彼此的私有成员。

It's less clear that "t.privateInt" should be visible, because t is a separate instance of class Test and we are not executing inside its equals method. However java allows this since both objects (t and this) are of the same class Test and can see each others private members.

这篇关于Java私有字段可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆