The “static” Keyword in Java

, , …,

Class Variable vs Instance Variable

“static” Keyword = Class Variable

Variables can be declared with the static keyword. Example:

static int y = 0;

When a variable is declared with the keyword static, its called a class variable.

No “static” Keyword = Instance Variable

Without the static keyword, it's called instance variable, and each instance of the class has its own copy of the variable.

// example of instance vs class variable

class T2 {
    int x = 0; // instance variable
    static int y = 0; // class variable

    void setX (int n) { x = n;}
    void setY (int n) { y = n;}

    int getX () { return x;}
    int getY () { return y;}

class T1 {
    public static void main(String[] arg) {
        T2 b1 = new T2();
        T2 b2 = new T2();


        // each b1 and b2 has separate copies of x
        System.out.println( b1.getX() );
        System.out.println( b2.getX() );

        // class variable can be used directly without a instance of it.
        //(if changed to T2.x, it won't compile)
        System.out.println( T2.y );
        T2.y = 7;
        System.out.println( T2.y );

        // class variable can be manipulated thru methods as usual
        System.out.println( b1.getY() );

Instance Method vs Class Methods

Methods can also be declared with the keyword static.

When a method is declared static, it can be used without having to create a object first.

For example, you can define a collection of math functions in a class, all static, using them like functions.

Methods declared with “static” keyword are called class methods. Otherwise they are instance methods.

// A class with a static method
class M2 { static int triple (int n) {return 3*n;}}

class M1 {
    public static void main(String[] arg) {

        // calling static methods without creating a instance
        System.out.println( M2.triple(4) );

        // calling static methods thru a instance is also allowed
        M2 m1 = new M2();
        System.out.println( m1.triple(5) );

Static Methods Cannot Access Non-Static Variables

Methods declared with static cannot access variables declared without static.

The following gives a compilation error, unless x is also static.

class V2 {
    int x = 3;
    static int returnIt () { return x;}

class V1 {
    public static void main(String[] arg) {
        System.out.println( V2.returnIt() );
~ $ javac error: non-static variable x cannot be referenced from a static context
    static int returnIt () { return x;}
1 error
~ $

Note: There's no such thing as static classs. static in front of class creates compilation error. However, there's a similar idea called abstract classes, with the keyword abstract. Abstract classes cannot be initialized. See: The “abstract” Keyword in Java.

blog comments powered by Disqus