【问题标题】:What is an instance variable in Java?Java中的实例变量是什么?
【发布时间】:2013-05-17 04:38:17
【问题描述】:

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

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

【问题讨论】:

标签: java instance-variables


【解决方案1】:

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

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

【讨论】:

  • 优秀的插图,用最简单的方式解释
【解决方案2】:

实例变量是类实例成员的变量(即,与使用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...)
  • 确实,为了方便访问,我已将大部分内容公开,这通常是个坏主意
猜你喜欢
  • 2011-11-29
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2022-09-23
  • 2010-10-19
  • 2012-08-13
相关资源
最近更新 更多