解释此代码中发生了什么? (帮助说明课程)

时间:2018-12-05 19:42:09

标签: java

我正在学习Java编程入门课程,但是我很难理解这段代码中到底发生了什么。有人可以帮助更好地解释它吗?

public class Foo {
    private int x;

    public Foo(int x) {
        this.x = x;
    }

    public void printVals(int x) {
        System.out.println(this.x);
        System.out.println(x);
    }

    public static void main(String[] args) {
        int x = 2;
        Foo a = new Foo(x);
        x += 4;
        Foo b = new Foo(x);
        x--;
        --x;
        a.printVals(x);
        x -= x;
        b.printVals(x);
        x += 1;
        System.out.println(x);
    }
}

1 个答案:

答案 0 :(得分:1)

public class Foo {
    private int x; //line 2

    public Foo(int x) {
        this.x = x;
    }

    public void printVals(int x) {
        System.out.println(this.x); //this.x == line 2.x
        System.out.println(x);//x==parameter x<-(int x)
    }

    public static void main(String[] args) {
        int x = 2; //local x == 2
        Foo a = new Foo(x);//a.x==2
        x += 4; //local x==6
        Foo b = new Foo(x);//b.x==6
        x--;//local x==5
        --x;//local x==4
        a.printVals(x);////a.x==2 && local x==4 
        x -= x;//local x == 0
        b.printVals(x);//b.x==6 && local x ==0
        x += 1;//local x==1
        System.out.println(x);//local x==1
    }
}
相关问题