Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Static variables

Tags:

java

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;
    }
       // ...
}

I learned in my class that Static variables should be accessed by calling with class name. i.e. ClassName.VariableName

But in the code above, how is this statement id = ++numberOfBicycles; compiled without errors, even though the variable numberOfBicycles is static

like image 589
Testaccount Avatar asked Jun 02 '13 06:06

Testaccount


People also ask

Can static variables be accessed in other methods?

A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.

How do you access static methods?

A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.

Can static variables be accessed by non-static method?

"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on the static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.


2 Answers

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.

like image 153
Aniket Thakur Avatar answered Oct 08 '22 03:10

Aniket Thakur


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.

like image 23
Juned Ahsan Avatar answered Oct 08 '22 02:10

Juned Ahsan