[英]Why is the Jshell not executing Methods cotaining Enum fields?
我有一個簡單的類。 Zelle 是一個簡單的枚舉。
public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
}
}
如果我想用 Jshell 打開這些方法,我會收到以下我不明白的錯誤:
jshell> Main.getZelle()
| Error:
| non-static method getZelle() cannot be referenced from a static context
| Main.getZelle()
| ^-----------^
jshell> Main.test()
| attempted to use class Main which cannot be instantiated or its methods invoked until variable Zelle is declared
jshell> Main.main(new String[0])
| attempted to use class Main which cannot be instantiated or its methods invoked until variable Zelle is declared
但是如果我在 IDE 中運行 main() 它將打印我的 test() 方法
public static void main(String[] args) {
test();
}
您正在以靜態方式訪問非靜態方法。 您可以通過創建類的對象來調用非靜態方法。 您的代碼將如下所示:
public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
Main main=new Main(); // this is the way to create an o object
main.getZelle(); //this is how you call a non-static method using class reference
main.getTest();
}
}
Main.getZelle()
您正在嘗試將方法getZelle()
作為靜態方法調用 - 它不是 - 因此出現錯誤消息,因為getZelle()
不是靜態方法。
Main.test()
test()
是一個靜態方法,但是它引用了Zelle
(您聲稱它是一個 枚舉,但您沒有發布它的定義)並且JShell不知道如何找到該enum
,因此會出現錯誤消息。 JShell正在嘗試編譯您的類Main
但它不能,因為Main
引用Zelle
並且JShell找不到Zelle
的定義。
Main.main(new String[0])
與Main.test()
相同的問題。
由於我在您的問題中找不到Zelle
的定義,所以我猜到它是什么並將其添加到您通過其編輯器輸入JShell的代碼中。 代碼如下。
enum Zelle {
Empty, RED
}
public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
}
}
現在,當我Main.main(new String[0])
輸入JShell時,代碼將執行並且我沒有收到任何錯誤消息。 但是請注意, Main.getZelle()
仍然會導致錯誤,因為getZelle()
不是靜態方法(正如我在上面解釋的那樣)。
我還建議您采用Java 命名約定。 Empty
應該是EMPTY
。
您應該聲明您的枚舉Zelle
並創建Main
類的實例以調用非靜態方法:
enum Zelle {
RED, Empty
}
final var main = new Main();
main.getZelle(); // RED
Main.test(); // Empty
Main.main(new String[0]); // HEllo World
您需要使用 jshell Nameofenum.java 將 Enum 導入 JShell。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.