How to declare a class and an interface in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell can provide an interactive shell for quickly prototyping, debugging, and learning Java and Java API without the need for the main() method or need to compile our code before executing it.

Declaration of Class:

We can declare a class just like we have written a code in Java Language. The JShell can detect when the class completes it.

In the below code snippet, we can declare a class Employee with two parameters and one method.

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> class Employee {
...>       String empName;
...>       int age;
...>
...>       public void empData() {
...>          System.out.println("Employee Name is: " + empName);
...>       }
...>    }
| created class Employee


In the below code snippet, we can create an object for Employee class and set values to empName, age.

jshell> Employee emp = new Employee()
emp ==> Employee@73846619

jshell> emp.empName = "Adithya"
$3 ==> "Adithya"

jshell> emp.age = 20
$4 ==> 20

jshell> emp.empData()
Employee Name is: Adithya


Declaration of an Interface:

We can also declare an interface similar to a class declaration. Once we have declared an interface, JShell detects when the declaration completes.

In the below code snippet, we can declare an interface Animal with three abstract methods.

jshell> interface Animal {
...>       public void eat();
...>       public void move();
...>       public void sleep();
...>    }
| created interface Animal


In the below code snippet, we got an error saying that the Cat class does not override the abstract methods defined by the Animal interface. It is similar to a class that implements an interface concept in Java language.

jshell> class Cat implements Animal {
...>    }
|    Error:
|    Cat is not abstract and does not override abstract method sleep() in Animal
|    class Cat implements Animal {
|    ^----------------------------
raja
Published on 03-Mar-2020 05:46:13
Advertisements