Accessing Static variables

后端 未结 8 1122
清歌不尽
清歌不尽 2020-12-31 09:50
public class Bicycle {

    private int cadence;
    private int gear;
    private int speed;
    private int id;
    private static int numberOfBicycles = 0;

    p         


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 10:35

    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.

    So your statement id = ++numberOfBicycles; is perfectly valid and will compile without errors.

提交回复
热议问题