代码之家  ›  专栏  ›  技术社区  ›  Hamza Belmellouki

为什么这个代码没有给我相同的结果?静态和静态{}的情况

  •  -1
  • Hamza Belmellouki  · 技术社区  · 7 年前

    我有一个问题,在静态与{}和静态没有{}有什么区别。如果有人向我解释这两个代码之间的区别,我就会理解:为什么第一个代码会给我一个编译时错误?以及如何将static关键字与{}一起使用。

    请查看我的第一个代码,其中有编译时错误:

    public class Lambdas {
    
    @FunctionalInterface
    public interface Calculate {
        int calc(int x, int y);
    
    }
    
    static {
    
        Calculate add = (a, b) -> a + b;
        Calculate difference = (a, b) -> Math.abs(a-b);
        Calculate divide = (a,b) -> b!=0 ? a/b : 0;
        Calculate multiply = (c, d) -> c * d ;
    
    }
    
    public static void main(String[] args) {
    
        System.out.println(add.calc(3,2)); // Cannot resole symbol 'add'
        System.out.println(difference.calc(5,10));  // Cannot resole symbol 'difference'
        System.out.println(divide.calc(5, 0));  // Cannot resole symbol 'divide'
        System.out.println(multiply.calc(3, 5));  // Cannot resole symbol 'multiply'
    
    }
    
    
    }
    

    第二个代码段工作正常:

    public class Lambdas {
    
    @FunctionalInterface
    public interface Calculate {
        int calc(int x, int y);
    
    }
    
    
    static Calculate add = (a, b) -> a + b;
    static Calculate difference = (a, b) -> Math.abs(a - b);
    static Calculate divide = (a, b) -> b != 0 ? a / b : 0;
    static Calculate multiply = (c, d) -> c * d;
    
    
    public static void main(String[] args) {
    
        System.out.println(add.calc(3, 2)); 
        System.out.println(difference.calc(5, 10)); 
        System.out.println(divide.calc(5, 0));  
        System.out.println(multiply.calc(3, 5));  
    }
    
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Dheeraj Joshi    7 年前

    这是一个静态初始化块:

     static {
    
    Calculate add = (a, b) -> a + b;
    Calculate difference = (a, b) -> Math.abs(a-b);
    Calculate divide = (a,b) -> b!=0 ? a/b : 0;
    Calculate multiply = (c, d) -> c * d ;
    
     }
    

    一个类可以有任意数量的静态初始化块,它们可以出现在类主体的任何位置。运行时系统保证按照静态初始化块在源代码中出现的顺序调用它们。

    有一种替代静态块的方法,您可以编写一个私有静态方法:

    class Whatever {
    public static varType myVar = initializeClassVariable();
    
    private static varType initializeClassVariable() {
    
        // initialization code goes here
    }
    }
    

    您的代码显示错误,因为变量(如add,difference)仅在这个静态{}块下有作用域,并且您不能在其他方法上访问它们,它们也类似于构造函数,所以当您实例化类时,代码也会运行

    来源 Oracle