Accessing Static variables

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

    May be what your lecturer said is regarding accessing them from outside the class not from inside the class. static variables can be accessed outside the class like this ClassName.VariableName or object.VariableName. But however the first method is preferrable.

    From inside the class it's not needed you may use this keyword or classname-qualifier to disambiguate with the local variables with the same name inside methods and constructors.

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

    Given your class ..

    public class Bicycle
    {
        private int cadence;
        private int gear;
        private int speed;
        private int id;
        private static int numberOfBicycles = 0;
    
        // ..
    }
    

    When I create an objects of type Bicycle, it will be like this:

    Bicycle a = new Bicycle (1,2,3);
    
    Bicycle b = new Bicycle (2,3,4);
    

    In memory, it's like this:

    [a] --> { id:1, cadence:1, gear:2, speed:3 }
    
    [b] --> { id:2, cadence:2, gear:3, speed:4 }
    

    numberOfBicycles is static, so it's not part of any Bicycle object, it's related to the class not an object, and so it will be like this in memory:

    [Bicycle] --> { numberOfBicycles:2 }
    

    And so to access the static member, first we define a static getter for it:

    public static int getNumberOfBicycles ()
    {
        return numberOfBicycles;
    }
    

    then we call it from the class:

    System.out.println(Bicycle.getNumberOfBicycles());
    
    0 讨论(0)
提交回复
热议问题