首頁 >Java >java教程 >如何在Java 9的JShell中實作封裝概念?

如何在Java 9的JShell中實作封裝概念?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB轉載
2023-09-02 22:01:02859瀏覽

如何在Java 9的JShell中实现封装概念?

Java Shell (簡稱JShell) 是用於學習Java和原型化Java程式碼的REPL互動工具。它會評估輸入的宣告語句表達式,並立即列印出結果並從命令列運行。

封裝是Java中的重要概念,用於確保「敏感」資料對使用者隱藏。為了實現這一點,我們必須將類別變數宣告為私有,並提供公共存取getset方法以及更新私有變數的值。

在下面的程式碼片段中,我們已經為Employee類別實作了封裝概念。

<strong>jshell> class Employee {
...>       private String firstName;
...>       private String lastName;
...>       private String designation;
...>       private String location;
...>       public Employee(String firstName, String lastName, String designation, String location) {
...>          this.firstName = firstName;
...>          this.lastName = lastName;
...>          this.designation = designation;
...>          this.location = location;
...>       }
...>      public String getFirstName() {
...>         return firstName;
...>      }
...>      public String getLastName() {
...>         return lastName;
...>      }
...>      public String getJobDesignation() {
...>         return designation;
...>      }
...>      public String getLocation() {
...>         return location;
...>      }
...>      public String toString() {
...>         return "Name = " + firstName + ", " + lastName + " | " +
...>                "Job designation = " + designation + " | " +
...>                "location = " + location + ".";
...>      }
...> }
| created class Employee</strong>

在下面的程式碼片段中,我們建立了一個Employee類別的實例,並列印出namedesignationlocation

<strong>jshell> Employee emp = new Employee("Jai", "Adithya", "Content Developer", "Hyderabad");
emp ==> Name = Jai, Adithya | Job designation = Content Developer | location = Hyderabad.</strong>

以上是如何在Java 9的JShell中實作封裝概念?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除