Accessing Static variables

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

    From within the class the Bicycle qualifier is optional on static variables, just like the this qualifier is optional on instance variables

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 10:30
     public int getID(){
        return numberOfBicycles;
    }
    
    public static int getNOB(){
        return numberOfBicycles;
    }
    


    In the Bicycle class

        Bicycle bc = new Bicycle(30, 90, 1);
        System.out.println(Bicycle.getNOB());
        System.out.println(bc.getID());
    
        Bicycle bc2 = new Bicycle(30,90, 1);
        System.out.println(Bicycle.getNOB());
        System.out.println(bc2.getID());
    
        Bicycle bc3 = new Bicycle(30,90, 1);
        System.out.println(Bicycle.getNOB());
        System.out.println(bc3.getID());
    
        Bicycle bc4 = new Bicycle(30,90, 1);
        System.out.println(Bicycle.getNOB());
        System.out.println(bc4.getID());
    


    In the main class of BicycleTest worked just fine for me

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 10:35

    you didn’t write Bicycle.numberOfBicycles. It isn’t necessary because we are already in that class so the compiler can infer it.

    0 讨论(0)
  • 2020-12-31 10:36

    Static variables are the shared variables. So you can access them using either the Classname.staticVariable or using an object of the class instance.staticVariable. In any case you will be referring to the single copy of the variable in memory, no matter how many objects you create.

    0 讨论(0)
提交回复
热议问题