如何用 Java 9 中的 JShell 实现封装概念?
Java Shell(简写JShell)是一种**交互式 REPL**工具,用于学习 Java 和原型化 Java 代码。它会根据输入来评估**声明**、**语句**和**表达式**,并立即打印结果并在命令行中运行。
封装是 Java 中一个重要的概念,用于确保将“敏感”数据隐藏起来,使其免受用户的侵害。要实现这一点,我们必须将类变量声明为私有的,并为get和set方法提供**public**访问权限,并更新私有变量的值。
在以下代码片段中,我们已经为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类的实例,它会打印一个name、designation和location。
jshell> Employee emp = new Employee("Jai", "Adithya", "Content Developer", "Hyderabad"); emp ==> Name = Jai, Adithya | Job designation = Content Developer | location = Hyderabad.
广告