简体   繁体   中英

Why does println() print this?

The following code prints out:

-7
-7
11 44 -54
11

I think it should print out:

-7
-7
-11 -44 -54
11

The code is:

import static java.lang.System.out;

public class Point {
    public static int x = 0;
    public int y = 0;
    public static int i = 7;
    public static void main(String[] args) {
        if (true) Point.x = -7;
        out.println(x);
        out.println(Point.x);
        Point foo = new Point(-11,-44,-54);
        Point bar = new Point(11,44,54);
            out.println(foo.x + " " + foo.i + " " + foo.y);
        out.println(Point.x);
    }

    //constructor
    public Point(int x, int i, int y) {
        this.y = y;
        this.i = i;
        this.x = x;
    }
}

If I remove Point bar = new Point(11,44,54); the output is:

-7
-7
-11 -44 -54
11

In case this is relevant: To run this program (which is inside Point.java ) I (like always) press Shift+Ctrl+F9 and Ctrl+F9 and Shift+F10. I'm running IntelliJ Idea 14.0.3 with JDK 7u76 on Win 8.1 64-bit with all updates installed.

Because x is static : there is only one instance of x that is "shared" for all instances of class Point . That's why the value gets overriden. In fact, x is not associated with any object but with the class itself. Note that this is not the case with variable y , which is an instance variable .

So in the following code:

Point foo = new Point(-11,-44,-54);
Point bar = new Point(11,44,54);

x is set to -11 then to 11 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM