static in Java

来源:互联网 发布:分析家炒股软件 编辑:程序博客网 时间:2024/06/05 11:51

 

 Variables with static

 

 variables can be declared with the static keyword. Example:

static int y=0;

When a variable is declared with the static keyword, its called a class variable. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to creat a instance.

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

In the following code, the class t2 has two variables x and y. The y is declared with the static keyword. In the main class t1, we try to manipulate the variables x and y in t2, showing the differences of instance variable and 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 x1 = new t2();
        t2 x2 = new t2();

        x1.setX(9);
        x2.setX(10);

        // each x1 and x2 has separate copies of x
        System.out.println( x1.getX() );
        System.out.println( x2.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
        x1.setY(t2.y+1);
        System.out.println( x1.getY() );
    }
}

 

Methods with static

 

Methods declared with static keyword are called class methods. Otherwise they are instance methods. When a method is declared static, it can be called/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. Example:

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

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

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

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


Notes:Methods declared with static cannot access variables declared without static. The following gives a compilation error, unless x is also static.

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

class t1 {
    public static void main(String[] arg) {
        System.out.println( t2.returnIt() );
    }
}

Note: There's no such thing as static classses. 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.

原创粉丝点击