JShell ให้ interactive shell สำหรับ prototyping, debugging, และเรียนรู้ Java/API อย่างรวดเร็ว ไม่ต้องมี main() method หรือคอมไพล์ก่อนรัน
การประกาศ Class
ประกาศคลาสได้เหมือนเขียนโค้ด Java ปกติ JShell ตรวจจับเมื่อคลาสสมบูรณ์
ตัวอย่าง: ประกาศคลาส Employee
C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro
jshell> class Employee {
...> String empName;
...> int age;
...>
...> public void empData() {
...> System.out.println("Employee Name is: " + empName);
...> }
...> }
| created class Employee
สร้าง Object และใช้งาน
jshell> Employee emp = new Employee()
emp ==> Employee@73846619
jshell> emp.empName = "Adithya"
$3 ==> "Adithya"
jshell> emp.age = 20
$4 ==> 20
jshell> emp.empData()
Employee Name is: Adithya
การประกาศ Interface
ประกาศ interface คล้ายคลาส JShell ตรวจจับเมื่อประกาศสมบูรณ์
ตัวอย่าง: ประกาศ Interface Animal
jshell> interface Animal {
...> public void eat();
...> public void move();
...> public void sleep();
...> }
| created interface Animal
Implement Interface
jshell> class Cat implements Animal {
...> }
| Error:
| Cat is not abstract and does not override abstract method sleep() in Animal
| class Cat implements Animal {
| ^----------------------------
Implement ให้ครบ
jshell> class Dog implements Animal {
...> public void eat() { System.out.println("Dog eating"); }
...> public void move() { System.out.println("Dog moving"); }
...> public void sleep() { System.out.println("Dog sleeping"); }
...> }
| created class Dog
jshell> new Dog().eat()
Dog eating
คำสั่งตรวจสอบใน JShell
- /classes - แสดง classes ทั้งหมด
- /interfaces - แสดง interfaces ทั้งหมด
- /types - แสดง classes, interfaces, enums ทั้งหมด
- /methods - แสดง methods ทั้งหมด
JShell ทำให้สร้างและทดสอบ classes/interfaces ได้ทันที เหมาะสำหรับ learning และ prototyping