为什么允许访问另一个对象的私有字段? [英] Why is it allowed to access a private field of another object?

查看:159
本文介绍了为什么允许访问另一个对象的私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我观察到了在Java中访问priavte字段的意外行为。请考虑以下示例,其中说明了行为:

Recently, I observed an unexpected behavior of accessing priavte fields in Java. Consider the following example, which illustrates the behavior:

public class A {

    private int i;  <-- private field!

    public A(int i) {
        this.i = i;
    }

    public void foo(A a) {
        System.out.println(this.i);  // 1. Accessing the own private field: good
        System.out.println(a.i);     // 2. Accessing private field of another object!
    }

    public static void main(String[] args) {
        (new A(5)).foo(new A(2));
    }
}

为什么我被允许访问另一个人的私人领域 foo 方法中的类 A 的对象(第二种情况)?

Why I am allowed to access the private field of another object of class A within the foo method (2nd case)?

推荐答案

私有字段保护类,而不是实例。主要目的是允许类独立于其API实现。在它们之间隔离实例,或者从同一类的静态代码中保护实例代码不会带来任何结果。

Private fields protect a class, not an instance. The main purpose is to allow a class to be implemented independently of its API. Isolating instances between themselves, or protecting the instance's code from the static code of the same class would bring nothing.

这篇关于为什么允许访问另一个对象的私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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