Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 静态和最终_Java - Fatal编程技术网

Java 静态和最终

Java 静态和最终,java,Java,我正试图编译这段代码 public class Foo { static final int x = 18; public void go(final int y){ System.out.println(x); } } public class Mixed2 { public static void main(String[] args){ Foo f = new Foo(); f.go(11);

我正试图编译这段代码

public class Foo {
    static final int x = 18;

    public void go(final int y){
        System.out.println(x);
    }
}

public class Mixed2 {
    public static void main(String[] args){

         Foo f = new Foo();
        f.go(11);
    }
}
并对其进行了编译。甚至给出了结果(18) 但这并不是必须的。为什么会这样? 我使用这个想法
谢谢

据我所知,您想知道为什么代码在以下情况下是有效的,而您希望它抛出一个错误

在这种情况下,您不是在更改字段
x
,而是简单地添加一个具有相同名称的新变量,以覆盖(阴影)字段
x

public class Foo {
    static final int x = 18; // field x

    // This creates a new variable x which hides the field x above
    public void go(final int x /* variable x */) {
        System.out.println(x);
    }
}
在接下来的两种情况下,您试图更改
x
,这将导致错误:

public class Foo {
    static final int x = 18; // field x

    // The field x is final and cannot be changed.
    public void go() {
        x += 1;
    }
}

public class Foo {
    static final int x = 18; // field x

    // The variable x is final and cannot be changed.
    public void go(final int x /* variable x */) {
        x += 1;
    }
}
旧答案:如果要打印
11
,应调用
System.out.println(y)
,而不是使用
x


尝试遵循一些Java教程,仔细查看代码和变量名。

事实是,您不能更改final的值。。。。然而,您并没有更改任何最终的数字,如果您更改了,您将得到编译器错误,而不是异常

了解静态和最终之间的差异很重要:

  • Static使变量在所有类之间都相同-将
    go()
    更改为Static仍将允许您访问它,但使
    go()
    为Static并从
    x
    中删除Static将阻止您引用
    x
    ,因为
    go()
    函数不知道在哪个
    Foo
    类中查找
    x
  • Final使变量不可更改-我不知道这有什么性能原因,但主要是常量。
    • 例如,您不希望能够将Boolean.TRUE的值设置为false


你说的“但这不一定是”是什么意思?它打印出常数的值,即18。你为什么还要别的?现在还不清楚是哪个方面让你困惑,以及你期望发生什么。我不会尝试编译这个。相反,我认为它不应该被编译。但是代码“publicvoidgo(finalintx){…}”也是编译的。但这是试图更改常量,应该会导致异常。是吗?@YeroSun当您将
final int x
作为函数的参数时,它会引入一个新变量,隐藏字段
static final int x
(它会对其进行阴影处理)。如果希望出现错误,则需要尝试在
go
内部分配
x
,但创建除已存在字段之外的任何其他变量
x
public class Foo {
    static final int x = 18;

    public void go(final int y) {

        // This is not possible because 'x' is final,
        // however the state of 'y' does not matter,
        // because its value is not being changed
        x = y;
        System.out.println(x);
    }
}

public class Mixed2 {
    public static void main(String[] args){

         Foo f = new Foo();
        f.go(11);
    }
}