public class Study{
private int a=0;
public void setA{
a=1;
}
public int getA{
return a;
}
public static void main(String[] args){
Study hello=new Study();
System.out.println("a:"+hello.a);
}
}
输出结果是a:0
这么说利用方法也不能改变private修饰的成员变量吗?
望解答,谢谢。public class Student{
private int a=0;
public void setA(){
a=1;
}
public int getA(){
return a;
}
public static void main(String[] args){
Student hello=new Student();
hello.setA(); //需要调用Student对象的setA方法。
System.out.println("a:"+hello.a); //输出结果: a:1
}
}private 只是将成员变量私有化,不能直接的去修改private 修饰的成员变量。而需要通过调用get/set 方法去对其进行修改。
方法没参数
setA方法你没有调用为a赋值,当然你的hello.a=0。