43

我的任务是制作一个带有实例变量的程序,一个字符串,应该由用户输入。但我什至不知道实例变量是什么。什么是实例变量?

如何创建一个?它有什么作用?

4

2 回答 2

79

实例变量是在类内部但在方法外部声明的变量:类似于:

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);
    }

}

这就是我们使用实例变量的方式。无耻的插件:这个例子是从这本免费的电子书这里提取

于 2013-05-22T08:14:58.703 回答
30

实例变量是作为类实例成员的变量(即,与用 a 创建的事物相关联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"
    }
}
于 2013-05-22T08:04:57.760 回答