我的任务是使用一个应该由用户输入的实例变量String来创建一个程序。但我甚至不知道实例变量是什么。什么是实例变量?我该如何创建一个?它做了什么?
答案 0 :(得分:67)
实例变量是在类中声明的变量,但在方法之外:类似于:
class IronMan{
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters / setters here **/
}
现在可以在其他类中实例化IronMan类以使用这些变量,例如:
class Avengers{
public static void main(String[] a){
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
这就是我们使用实例变量的方式。无耻的插件:这个免费电子书的例子来自here。
答案 1 :(得分:26)
实例变量是一个变量,它是类实例的成员(即与使用new
创建的内容相关联),而类变量是类本身的成员。
类的每个实例都有自己的实例变量副本,而每个静态(或类)变量只有1个与类本身相关联。
difference-between-a-class-variable-and-an-instance-variable
此测试类说明了差异
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 1
//(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"
}
}