Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

java - Why is it allowed to access a private field of another object?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...