Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

กฎสำหรับ External Declarations ใน JShell Java 9

JShell เป็น command-line tool ใน Java 9 เป็น REPL tool แรกของ Java สร้างสภาพแวดล้อมเขียนโปรแกรมง่ายๆ อ่าน input ประเมินผลพิมพ์ result

Declarations นอก class หรือ interface (รวม declarations ของ classes และ interfaces เอง) สร้างภายใต้กฎต่อไปนี้:

กฎสำหรับ External Declarations

1) Access Modifiers ถูก Ignore

public, protected, private ถูก ignore ทุก declarations เข้าถึงได้ทั้งหมด


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

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

2) Modifier final ถูก Ignore

เปลี่ยนแปลงและ inheritance ได้


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) Modifier static ถูก Ignore

เพราะไม่มี container class


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

4) Modifiers default และ synchronized ห้ามใช้


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

5) Modifier abstract อนุญาตเฉพาะใน Classes


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

jshell> abstract class B { abstract void m(); }
| created class B

สรุปตาราง Modifiers ใน JShell Top-level

Modifier Allowed Behavior
public Ignored (warning) All accessible
protected Ignored (warning) All accessible
private Ignored (warning) All accessible
final Ignored (warning) Can reassign/extend
static Ignored (warning) No container class
default Error Not allowed
synchronized Error Not allowed
abstract Classes only Methods: Error
strictfp Ignored (warning) No effect
native Error Not allowed
transient Error Not allowed
volatile Error Not allowed

เหตุผลและการออกแบบ

  • JShell เป็น REPL - ความยืดหยุ่นสำคัญกว่า encapsulation
  • Top-level declarations อยู่ใน implicit "scratch" class
  • ทุกอย่าง visible กันหมด เพื่อความสะดวกในการทดลอง
  • Nested declarations (ใน class/interface) ใช้ modifiers ได้ปกติ

Nested Context Example


jshell> class Outer {
   ...>     private int x = 10;           // OK - nested
   ...>     static void sm() {}           // OK - nested
   ...>     synchronized void sync() {}   // OK - nested
   ...>     abstract void abs();          // OK - nested (in abstract class)
   ...> }
| created class Outer