Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

java - static variable vs non static variable

I have defined an object and declared a static variable i. In the get() method, when I try to print the instance and class variable, both print the same value.

Isn't this.i an instance variable? Should it print 0 instead of 50?

public class test {
    static int i = 50;
    void get(){
        System.out.println("Value of i = " + this.i);
        System.out.println("Value of static i = " + test.i);
    }

    public static void main(String[] args){
        new test().get();
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, there's only one variable - you haven't declared any instance variables.

Unfortunately, Java lets you access static members as if you were accessing it via a reference of the relevant type. It's a design flaw IMO, and some IDEs (e.g. Eclipse) allow you to flag it as a warning or an error - but it's part of the language. Your code is effectively:

System.out.println("Value of i = " + test.i);
System.out.println("Value of static i = " + test.i);

If you do go via an expression of the relevant type, it doesn't even check the value - for example:

test ignored = null;
System.out.println(ignored.i); // Still works! No exception

Any side effects are still evaluated though. For example:

// This will still call the constructor, even though the result is ignored.
System.out.println(new test().i);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...