Java中的实例变量是什么?

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

2
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html - Maroun
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);
    }

}

这就是我们如何使用实例变量。不要害羞地插一句广告:这个示例摘自这本免费电子书here


31

实例变量是类的实例(即使用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"
    }
}

你可以把实例变量看作对象中的“字段”。相关概念是封装(参见:私有访问修饰符、getter 和 setter...)。 - vikingsteve
的确,我已将大多数东西声明为公共以便易于访问,但这通常是一个不好的主意。 - Richard Tingle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接