【问题标题】:How we can define the scope in java? [closed]我们如何在java中定义范围? [关闭]
【发布时间】:2015-11-19 05:56:46
【问题描述】:

我们如何在java中定义范围? 例如:

public class ScopeTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x=10;
        if(x==10){
            x=20;
            System.out.println("X:" +x);
            System.out.println("X:" +x);
        }

    }

}

输出:

X:20
X:20

我想要:

X=20
X=10

【问题讨论】:

  • 你不能做你想做的事。
  • 考虑将变量命名为不同的名称...?
  • 你认为你为什么要这样做?
  • 这个模型程序是错误的。你声明了一个变量 x=10。你改变它然后改变将是结果。这里没有什么特别的范围。如果您在 if{} na 中重新声明,这将是有意义的。

标签: java scope


【解决方案1】:

当前作用域内只能有一个局部变量。

你可以做的是有一个变量作为成员和一个局部变量。

class ScopeTest {
    static int x = 10;

    public static void main(String[] args) {
        if (x == 10) {
            int x = 20;
            System.out.println("X:" + x);
            System.out.println("X:" + ScopeTest.x);
        }
    }
}

注意:如果你也有继承的实例,你可以使用super.x

class ScopeTest {
    int x = -10;

    public static void main(String[] args) {
        new SubClassTest().printX();
    }
}

class SubClassTest extends ScopeTest {
    static int x = 10;

    public void printX() {
        if (x == 10) {
            int x = 20;
            System.out.println("x:" + x);
            System.out.println("SubClassTest.x:" + SubClassTest.x);
            System.out.println("super.x:" + super.x);
        }

    }
}

打印

x:20
SubClassTest.x:10
super.x:-10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多