大哥,你这叫访问私有变量吗???我晕,public String getOther(A other) 这个方法明明就是public,其他类是通过访问getOther方法才能访问到String a的,实际上是其他类在访问getOther方法,getOther方法再访问String a,你自己要搞清楚哦,不要乱讲,否则java就死在你手上了,你不调用getOther方法,直接访问A.a试试,肯定是权限错误。无知者无畏啊,什么都敢讲,汗~~~~~
调试欢乐多
public String getOther(A other) 2.public String getOther(A other)
其他类有办法直接给A.a赋值吗,不没有,只有通过set(String a)实现。
记住这个吧
私有变量是类私有不是对象私有,是为了避免暴露类内部细节而设定的。其实跟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);
}
}
比如:学生是一个类,有姓名私有的,而小B是一个学生,那么对于学生类来说,当然知道小B肯定是有姓名的。这个和私有变量的意义没有关系,更何况我们本来就是通过方法例如setName()/getName()来访问私有变量name的。
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()来实现,那么也就是说,同一个类的不同对象之间可以互相直接取得私有成员的值,但不同类的对象却只能通过共有方法来取得私有成员的值。我就是对这些有点不理解,希望大家给予解释。