访问静态变量 [英] Accessing Static variables
问题描述
public class Bicycle {
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;
id = ++numberOfBicycles;
}
// ...
}
我学到了在我的班级中应该通过使用类名
进行调用来访问静态变量。 ie ClassName.VariableName
I learned in my class that Static variables should be accessed by calling with class name
. i.e. ClassName.VariableName
但是在上面的代码中,这个语句是怎么回事 id = ++ numberOfBicycles;
编译时没有错误,即使变量 numberOfBicycles
是 static
But in the code above, how is this statement id = ++numberOfBicycles;
compiled without errors, even though the variable numberOfBicycles
is static
推荐答案
静态变量由类而不是其各个实例(对象)拥有。引用类外部的静态变量是通过 ClassName.myStaticVariable
,但在类中它与其他实例变量类似。
Static variables are owned by class rather than by its individual instances (objects). Referring static variables outside the class is by ClassName.myStaticVariable
but inside the class it is similar to other instance variables.
你总是可以在非静态方法中使用静态变量但是你不能在静态方法中使用非静态变量当静态方法加载其他非静态实例变量时没有创建。
You can always use static variables in non-static methods but you cannot use non-static variables in static methods reason being when static methods are loaded other non-static instance variables are not created.
所以你的语句 id = ++ numberOfBicycles;
完全有效,编译时没有错误。
So your statement id = ++numberOfBicycles;
is perfectly valid and will compile without errors.
这篇关于访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!