在Java中,如果这样写,为什么私有数据成员可以在类外访问?

问题描述

通常,如果 type 是名为 Pass 的类的 private 成员,并且 obj 是对 Pass 类的对象的引用,我们不能做 obj.type 因为 typeprivate 成员,所以会出错。

copy() 方法中,a 作为参数传递,其中 a 是对 Pass 对象的引用。

按照同样的逻辑,我们也不应该被允许做 a.type

但是这段代码运行良好。为什么?这是我的疑问。

public class Main {

    public static void main(String[] args) {
    Pass ob1 = new Pass(10,'c');
    Pass ob2 = new Pass(20,'f');

    ob1.print();
    ob2.print();

    ob1.copy(ob2);

    ob1.print();
    ob2.print();
    }
}

class Pass {
    private int number = 0;
    private char type = 'a';

    public Pass(int i,char t) {
        this.number = i;
        this.type = t;
    }

    public void copy(Pass a) {
        this.number = a.number;
        this.type = a.type;
    }

    public void print() {
        System.out.println(number + " =>" + type);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)