Friday, 8 January 2021

Jshell: Working with Classes

Step 1: Open terminal and execute the command ‘jshell’ to see the jshell prompt.

$jshell
|  Welcome to JShell -- Version 10.0.2
|  For an introduction type: /help intro

jshell>

 

Step 2: Copy and execute below snippet in jshell prompt.

 

Employee.java

public class Employee {
	private int id;
	private String firstName;
	private String lastName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

 

jshell> public class Employee {
   ...>     private int id;
   ...>     private String firstName;
   ...>     private String lastName;
   ...> 
   ...>     public int getId() {
   ...>         return id;
   ...>     }
   ...> 
   ...>     public void setId(int id) {
   ...>         this.id = id;
   ...>     }
   ...> 
   ...>     public String getFirstName() {
   ...>         return firstName;
   ...>     }
   ...> 
   ...>     public void setFirstName(String firstName) {
   ...>         this.firstName = firstName;
   ...>     }
   ...> 
   ...>     public String getLastName() {
   ...>         return lastName;
   ...>     }
   ...> 
   ...>     public void setLastName(String lastName) {
   ...>         this.lastName = lastName;
   ...>     }
   ...> 
   ...> }
|  created class Employee

 

Step 3: Let’s create an Employee object by executing below statement.

var emp = new Employee()

 

jshell> var emp = new Employee()

emp ==> Employee@239963d8

 

Execute following statements to populate employee details.

 

emp.setId(1)

emp.setFirstName("Krishna")

emp.setLastName("Ponnam")

 

jshell> emp.setId(1)

jshell> emp.setFirstName("Krishna")

jshell> emp.setLastName("Ponnam")

 

Step 4: Now you can execute below statements to get the property values associated with employee instance.

 

emp.getId()

emp.getFirstName()

emp.getLastName()

 


jshell> emp.getId()
$6 ==> 1

jshell> emp.getFirstName()
$7 ==> "Krishna"

jshell> emp.getLastName()
$8 ==> "Ponnam"

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment