Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách khai báo class và interface trong JShell Java 9

JShell cung cấp shell tương tác cho prototyping, debugging, học Java/API nhanh – không cần main() hay compile trước.

Khai báo Class

Viết như Java bình thường. JShell detect khi class hoàn tất (khớp ngoặc).

Ví dụ: Class Employee

C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> class Employee {
   ...>     String empName;
   ...>     int age;
   ...>     public void empData() {
   ...>         System.out.println("Employee Name is: " + empName);
   ...>     }
   ...> }
| created class Employee

Tạo object, set field, gọi method

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

Khai báo Interface

Tương tự class. JShell detect khi declaration complete.

Ví dụ: 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 {
|  ^----------------------------

JShell enforce interface contract như Java bình thường – phải implement tất cả abstract method.

Implement đúng

jshell> class Cat implements Animal {
   ...>     public void eat() { System.out.println("Cat eating"); }
   ...>     public void move() { System.out.println("Cat moving"); }
   ...>     public void sleep() { System.out.println("Cat sleeping"); }
   ...> }
| created class Cat

jshell> new Cat().eat()
Cat eating

Tính năng JShell cho Class/Interface

  • Redefine class: Gõ lại class cùng tên → replace (warning).
  • Forward reference: Dùng class/interface trước khi khai báo (trong method body).
  • Tab completion: Gõ emp. + Tab → xem method/field.
  • /list: Xem tất cả class/interface đã khai báo.
  • /drop <id>: Xóa class/interface khỏi session.

JShell biến việc học OOP, test interface implementation thành trải nghiệm interactice, immediate feedback.