大哥,你这叫访问私有变量吗???我晕,public String getOther(A other) 这个方法明明就是public,其他类是通过访问getOther方法才能访问到String a的,实际上是其他类在访问getOther方法,getOther方法再访问String a,你自己要搞清楚哦,不要乱讲,否则java就死在你手上了,你不调用getOther方法,直接访问A.a试试,肯定是权限错误。无知者无畏啊,什么都敢讲,汗~~~~~

解决方案 »

  1.   

    1.你已经告诉了他人可以让他人拿了,别人为什么不拿呢?
    public String getOther(A other) 2.public String getOther(A other) 
    其他类有办法直接给A.a赋值吗,不没有,只有通过set(String a)实现。
      

  2.   

    声明该Field的类中的method可以访问private field。
    记住这个吧
      

  3.   

    同意 wolfsquare(狼平方) 的观点:
     私有变量是类私有不是对象私有,是为了避免暴露类内部细节而设定的。其实跟getOther(A other) 函数无关。
    我将上面的代码改变一下就可以看出。
    public class testFunc2 {
    private String a;
    public void set(String a) {
    this.a=a;
    }
             //*********************************
    public String getOther(testFunc2 other) {
    return other.a;
    }
             //*******************************
    public static void main(String[] arc) {
    testFunc2 other=new testFunc2();
    other.set("world");
    String value=other.a ;   //直接取私有变量。
    System.out.println(value);
    }
    }
      

  4.   

    谢谢各位的解释,我也很同意私有变量是类私有不是对象私有,是为了避免暴露类内部细节而设定的。从设定方法和语言规则来说,都是没有错的。关于大家说的getOther()方法为共有的理由,我觉得这不是根本原因,比如,我们将getOther()方法改为private的,结果依然。
      

  5.   

    我想是这样的,因为getother方法的参数是A类型的对象,而getother方法又是其类A的方法,所以对于类A 来说,其实例的特征是知道的,不管你告诉他还是没有告诉。
    比如:学生是一个类,有姓名私有的,而小B是一个学生,那么对于学生类来说,当然知道小B肯定是有姓名的。这个和私有变量的意义没有关系,更何况我们本来就是通过方法例如setName()/getName()来访问私有变量name的。
      

  6.   

    我将程序改造了一下:
    class B {
    private String b;
    public void set(String b) {
    this.b=b;
    }
    public String get() {
    return this.b;
    }
    }
    public class A {
    private String a;
    private void set(String a) {
    this.a=a;
    }
    private String getOther1(A a) {
    return a.a;
    }
    private String getOther2(B b) {
    //return b.b;
    return b.get();
    }
    }
    这时候,我们可以通过return a.a取得A类的对象a的私有成员a,而要取得B类的对象b的私有变量b则只能通过对象b的共有方法b.get()来实现,那么也就是说,同一个类的不同对象之间可以互相直接取得私有成员的值,但不同类的对象却只能通过共有方法来取得私有成员的值。我就是对这些有点不理解,希望大家给予解释。
      

  7.   

    我上面的已经说明了!其实你的私有成员对自己的类里面是没有办法隐藏的,和方法本身是否私有没有关系,对其他类就不一样了,需要通过public(其提供的接口)来访问