【发布时间】:2013-05-17 04:38:17
【问题描述】:
我的任务是制作一个带有实例变量的程序,一个字符串,应该由用户输入。但我什至不知道实例变量是什么。什么是实例变量?
如何创建一个?它有什么作用?
【问题讨论】:
我的任务是制作一个带有实例变量的程序,一个字符串,应该由用户输入。但我什至不知道实例变量是什么。什么是实例变量?
如何创建一个?它有什么作用?
【问题讨论】:
实例变量是在类内部但在方法外部声明的变量:类似于:
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 创建的东西相关联),而类变量是类本身的成员。
类的每个实例都有自己的实例变量副本,而每个静态(或类)变量只有一个与类本身关联。
What’s the 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 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"
}
}
【讨论】:
field。一个相关的概念是封装(参见:private 访问修饰符、getter 和 setter...)