如何在Java 9中的JShell中实现封装概念?
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 类的实例,并打印了名称,名称和位置。
jshell> Employee emp = new Employee("Jai", "Adithya", "Content Developer", "Hyderabad");emp ==> Name = Jai, Adithya | Job designation = Content Developer | location = Hyderabad.
以上是 如何在Java 9中的JShell中实现封装概念? 的全部内容, 来源链接: utcz.com/z/322173.html