Java中的“每行一个声明”和“每行多个变量赋值”有区别吗?或者如何解释这种行为?

问题描述 投票:0回答:1
public class ThisKeywordDemo1 {
    int x = 10;
    int y = 20;
    
    public static void main(String[] args) {
        ThisKeywordDemo1 tkd = new ThisKeywordDemo1();
        tkd.getData();
    }

    public void getData(){
        //int a = x = 50;
        //int b = y = 40;

        int x = 50;
        int y = 40;
        int a = 50;
        int b = 40;

        System.out.println(a + b);
        System.out.println(x + y);
        System.out.println(this.x + this.y);

    }
}

在上面的代码片段中,输出是 90 90 30,这是预期的。

        int a = x = 50;
        int b = y = 40;

        //int x = 50;
        //int y = 40;
        //int a = 50;
        //int b = 40;

但是当注释行被取消注释并且一行声明被注释时,输出变为 90 90 90, 你们谁能解释一下这种行为吗?

java this variable-assignment
1个回答
0
投票

这是两种情况

案例:A

    int a = x = 50; // int a = this.x = 50;
    int b = y = 40; // int b = this.y = 50

案例:B

    int x = 50; // introduce method local x, this.x stays 10
    int y = 40; // introduce method local y, this.y stays 20
    int a = 50;
    int b = 40;

因此,在第二种情况下,您可以使用局部变量隐藏类字段。

© www.soinside.com 2019 - 2024. All rights reserved.