我的主类中有一个私有变量,是否可以在不将其设为受保护变量的情况下在其他类中使用它?
答案 0 :(得分:4)
不。这就是private
与protected
的重点。 the Oracle Java member access tutorial中的详细信息,该功能还具有以下表格:
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | **Access Levels** | +−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+ | Modifier | Class | Package | Subclass | World | +−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+ | public | Y | Y | Y | Y | | protected | Y | Y | Y | N | | (no modifier) | Y | Y | N | N | | private | Y | N | N | N | +−−−−−−−−−−−−−−−+−−−−−−−+−−−−−−−−−+−−−−−−−−−−+−−−−−−−+
答案 1 :(得分:1)
私有成员变量仅限于该类,但是您可以引入setter和getter方法来访问它们。这是encapsulation的一部分。
从上面的URL(教程点)中获得一个示例,我们有3个私有值,分别具有setter和getter方法,可根据需要检索或设置该值:
/* File name : EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}