Java Shell (简称JShell) 是一个用于学习Java和原型化Java代码的REPL交互工具。它会评估输入的声明、语句和表达式,并立即打印出结果并从命令行运行。
封装是Java中的一个重要概念,用于确保“敏感”数据对用户隐藏。为了实现这一点,我们必须将类变量声明为私有,并提供公共访问get和set方法以及更新私有变量的值。
在下面的代码片段中,我们已经为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类的实例,并打印出name、designation和location。
<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中文网其他相关文章!