Java 9 中 JShell 的外部宣告規則是什麼?


JShellJava 9 中引入的 命令列工具,它是 Java 第一個正式的 REPL 工具,用於建立簡單的程式設計環境,讀取使用者的輸入,對其進行評估,並列印結果。

介面 之外的宣告(以及類和介面本身的宣告)是在以下規則下建立的。

外部宣告規則

1) 可以忽略訪問修飾符,如 public、protectedprivate。所有宣告片段都可以被其他所有片段訪問。

jshell> private int i = 10;
i ==> 10

jshell> System.out.println(i);
10

2) 可以忽略修飾符 final。允許更改和繼承。

jshell> final class A {void m() {} }
|   Warning:
|   Modifier 'final' not permitted in top-level declarations, ignored
|   final class A {void m() {} }
|   ^---^
|   created class A

3) 可以忽略修飾符 static,因為沒有容器類。

jshell> static char letter = 'A;
|   Warning:
|   Modifier 'static' not permitted in top-level declarations, ignored
|   static char letter = 'A';
|   ^----^
letter ==> 'A'

4) 不允許使用修飾符 defaultsynchronized

jshell> synchronized void method() {}
|   Error:
|   Modifier 'synchronized' not permitted in top-level declarations
|   synchronized void method() {}
|   ^----------^

5) 修飾符 abstract 僅允許在類中使用。

jshell> abstract void method();
|   Error:
|   Modifier 'abstract' not permitted in top-level declarations
|   abstract void method();
|   ^------^

更新於: 2020年4月16日

85 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告