Accessing Static variables

后端 未结 8 1123
清歌不尽
清歌不尽 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:27

    Non static methods can access static members of a class because only a single copy of the static variable exists unlike instance variables which are only created once a new object of that type has been created.
    I recommend you have another class to test,like BicycleTest which will have the main class and then create maybe 4Bicycle objects and using 2getters in the Bicycle class retrieve the numberofBicycles and ID everytime you create an object maybe that will give you a picture of what is happening.

提交回复
热议问题