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

javaobject oriented programmingprogramming

Java Shell(简称 JShell)是一个 REPL  交互式工具,用于学习 Java 和原型化 Java 代码。它会评估输入的 声明语句表达式,并立即打印出结果并从命令行运行。

封装是 Java 中的一个重要概念,用于确保"敏感"数据已对用户隐藏。为了实现这一点,我们必须将类变量声明为私有变量,并提供对get set 方法 公共访问权限,并更新私有变量的值。

在下面的代码片段中,我们为Employee类实现了封装概念。

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

在下面的代码片段中,我们创建了一个 Employee  类的实例,并打印出 namedesignationlocation

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

相关文章