什么是Java中的实例变量? [英] What is an instance variable in Java?
问题描述
我的任务是制作一个带有实例变量(字符串)的程序,该变量应该由用户输入.但是我什至不知道什么是实例变量.什么是实例变量?
My assignment is to make a program with an instance variable, a string, that should be input by the user. But I don't even know what an instance variable is. What is an instance variable?
如何创建一个?它是做什么的?
How do I create one? What does it do?
推荐答案
实例变量是在类内部但在方法外部声明的变量:
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
现在,可以在另一个类中实例化此IronMan类以使用这些变量.像这样:
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
这是我们使用实例变量的方式.无耻的插件:此示例摘自此免费电子书的此处此处.
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
这篇关于什么是Java中的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!