我对 Java 很陌生。我写了一个小程序来了解封装和访问方法。代码是:
package practise;
public class EncapTest {
private String name;
String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package practise;
public class RunEncap {
public static void main(String[] args) {
EncapTest encapObj = new EncapTest();
encapObj.setName("Prabh");
encapObj.surname = "Rana";
System.out.println("Name :" + encapObj.getName());
System.out.println("Surname :" + encapObj.surname);
}
}
现在,如果我创建另一个包“practice2”并使用导入并尝试创建“EncapTest”的对象,我可以访问变量名称,但是当我尝试访问姓氏时,它显示字段姓氏不可见的错误..
package practise2;
import practise.EncapTest;
public class Runencap2 {
public static void main(String[] args) {
EncapTest encapObj = new EncapTest();
encapObj.setName("Prabh");
encapObj.surname = "Rana"; // <<<<getting error here
System.out.println("Name :" + encapObj.getName());
System.out.println("Surname :" + encapObj.surname);
}
}