Java - 什么是实例变量?

aqu*_*qua 36 java instance-variables

我的任务是使用一个应该由用户输入的实例变量String来创建一个程序.但我甚至不知道实例变量是什么.什么是实例变量?我该如何创建一个?它有什么作用?

Yas*_*rma 70

实例变量是在类中声明的变量,但在方法之外:类似于:

class IronMan{

     /** These are all instance variables **/
     public String realName;
     public String[] superPowers;
     public int age;

     /** Getters / setters here **/
}
Run Code Online (Sandbox Code Playgroud)

现在,这个IronMan类可以在其他类中实例化以使用这些变量,例如:

class Avengers{
        public static void main(String[] a){
              IronMan ironman = new IronMan();
              ironman.realName = "Tony Stark";
              // or
              ironman.setAge(30);
         }

}
Run Code Online (Sandbox Code Playgroud)

这就是我们使用实例变量的方式.无耻插头:来自实例本免费的电子书拉到这里这里.


Ric*_*gle 28

实例变量是一个变量,它是类实例的成员(即与用a创建的东西相关联new),而类变量是类本身的成员.

类的每个实例都有自己的实例变量副本,而每个静态(或类)变量只有1个与类本身相关联.

差之间-A-类变量和 - 一个实例变量

这个测试类说明了差异

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"
    }
}
Run Code Online (Sandbox Code Playgroud)