[英]why this code don't give me the same result ? situation with static and static {}
我在使用 {} 的靜態問題和沒有 {} 的靜態問題上有什么區別。 如果有人向我解釋這兩個代碼之間的區別,我會理解:為什么第一個代碼給我一個編譯時錯誤? 以及如何在 {} 中使用 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));
}
}
這是一個靜態初始化塊:
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)僅在此 static{} 塊下具有作用域,而您無法在其他方法上訪問它們,它們也與構造函數類似,因此當您實例化班級
源甲骨文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.