来共享类之间的变量,有三种方式:
public class Human {
// instance variables
public String name;
public int age;
//constructor, creates an instance of the Human class.
public Human(String s, int i){
name = s;
age = i;
}
}
在这种情况下
,你的实例变量是公开的。 所以在另一个类,当你创建一个人力类的实例调用:
Human aHuman = new Human(tom, 25);
那么你就可以直接访问这两个实例变量。您可以通过使用得到其数值:
String theHumanName = aHuman.name;
,您可以通过使用其值设置(修改):如果你的变量是公共
aHuman.name = "mike";
两个以上的线路才有效。你应该让他们保持私密的原因是保持课堂以外的价值观。所以如果他们是私人的,那么你可以根据需要创建get和set方法。 这里是如何要做到:
public class Human {
// instance variables
private String name;
private int age;
//constructor, creates an instance of the Human class.
public Human(String s, int i){
setName(s);
setAge(i);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
现在从类的外部
,您可以拨打:
String theHumanName = aHuman.getName(); // this a method call, therefore you must have the parentheses
,您可以通过使用其值设置(修改):
aHuman.setName("mike");
其他班级是否是一个子班级?另外,请遵循Java命名约定('name')。 –
那么如果你从另一个类中扩展这个类,那么这些变量将全部都是可访问的。事实上,因为您将变量设置为“公共”,他们可以在任何地方访问。 –
这没有意义:您从*对象*中获取信息不是来自类,更不是*抽象*类。你的问题是一个[XY问题](http://mywiki.wooledge.org/XyProblem),当你问最好的解决方案是使用完全不同的方法时,如何解决特定的代码问题。仔细考虑一下你的问题,然后告诉我们你究竟想要做什么的细节,而不是你想如何解决它。 –