我的任务是创建一个带有实例变量的程序,这个变量是一个字符串,应该由用户输入。但我甚至不知道什么是实例变量。什么是实例变量?如何创建一个?它有什么作用?
实例变量是在类中声明但在方法之外的变量:类似于:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
现在,可以在其他类中实例化这个IronMan类以使用这些变量。就像这样:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
这就是我们如何使用实例变量。不要害羞地插一句广告:这个示例摘自这本免费电子书here。
实例变量是类的实例(即使用new
创建的东西)的成员变量,而类变量是类本身的成员变量。
类的每个实例都有其自己的实例变量副本,而每个静态(或类)变量只有一个,与类本身相关联。
这个测试类说明了它们之间的区别:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}