有 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);
    }
}

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


共 (2) 个答案

  1. # 1 楼答案

    事实是,你不能改变一个final的值。。。但是,您没有更改任何最终数字,如果更改了,则会出现编译器错误,而不是异常

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

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

    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);
        }
    }
    
  2. # 2 楼答案

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

    在这种情况下,您不是在更改字段x,而是简单地添加一个同名的新变量,该变量覆盖(shadows)字段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教程,仔细查看代码和变量名