Open In App

How to create a Class in JShell of Java 9

Last Updated : 14 Feb, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

JShell is an interactive Java Shell tool, it allows us to execute Java code from the shell and shows output immediately. JShell is a REPL (Read Evaluate Print Loop) tool and runs from the command line. Jshell have the facility to create a class by which all the efforts can be reduced to write a whole Java code to check the class is working properly or not.

A class contains different methods and variables according to user requirements but the program doesn’t work due to some errors. But with the help of JShell, this can be resolved more efficiently and can be less time-consuming.

Example:

  1. In this example, class A is created successfully and one can call the class methods by creating an object of class A.




    C:\Windows\SysWOW64>jshell
    |  Welcome to JShell -- Version 13.0.1
    |  For an introduction type: /help intro
    jshell> class A{
       ...> int x;
       ...> int y;
       ...> void get(int a, int b)
       ...> {
       ...> x=a;
       ...> y=b;
       ...> }
       ...> void show()
       ...> {
       ...> System.out.println("sum="+(x+y));
       ...> }
       ...> }
      
    |  created class A

    
    

  2. In this example, due to ‘;’, an error occurs and this can be solved it easily because the line of code is small and easy.




    jshell> class A{
       ...> int x;
       ...> int y;
       ...> void get(int a, int b)
       ...> {
       ...> x=a;
       ...> y=b;
       ...> }
       ...> void show();
       ...> {
       ...> System.out.println("sum="+(x+y));
       ...> }
       ...> }
    |  Error:
    |  missing method body, or declare abstract
    |  void show();
    |  ^----------^

    
    

  3. Example to access the methods of the class:




    jshell>A a=new A();
    a ==> A@42dafa95
    jshell>a.get(10, 20);
    jshell>a.show();
    sum=30

    
    

  4. In the above examples, the objects of class A is created and denoted by ‘a’ and we call the get and show methods. We can also override the methods of class A. After overriding the methods, a message will be displayed that “the method is modified” and now we can call the modified methods and get the answers.




    jshell> void show();
       ...> {
       ...> System.out.println("sum="+(x-y));
       ...> }
    |  modified method show(int, int)

    
    



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads