java中局部变量_java中的局部变量和类变量的行为

我是Java编程语言的新手.

我熟悉C和C但无法理解下面程序的行为.

public class Test {

static int x = 11;

private int y = 33;

public void method1(int x) {

Test t = new Test();

this.x = 22;

y = 44;

System.out.println("Test.x: " + Test.x);

System.out.println("t.x: " + t.x);

System.out.println("t.y: " + t.y);

System.out.println("y: " + y);

}

public static void main(String args[]) {

Test t = new Test();

t.method1(5);

}

}

正确的输出:

Test.x: 22

t.x: 22

t.y: 33

y: 44

预期产量:

Test.x: 22

t.x: 22

t.y: 44 // As variable y is modified inside the function.

y: 44

甚至改变y = 44的线;到this.y = 44;没有给出预期的产出.

解决方法:

问题是你没有提到创建的实际对象.您正在从具有新变量的其他实例中获取变量.

Test t = new Test();

this.x = 22;

y = 44;

System.out.println("Test.x: " + Test.x);

System.out.println("t.x: " + t.x);

System.out.println("t.y: " + t.y);

System.out.println("y: " + y);

如果你仔细看第一行Test t = new Test();

你没有在y指定为44的特定实例上调用method1.因此,您可以看到顶级值.

如果重命名实例,将会更清楚.而不是总是.

这就是混淆的原因,而且你在里面调用method1()可能会导致无限循环.

标签:java,static,class-level

来源: https://codeday.me/bug/20190522/1153289.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值