En el tutorial anterior aprendimos cómo trabajar con variables en JShell. En esta guía, aprenderemos cómo crear métodos en JShell, cómo usarlos y cómo modificar la definición del método ya definida.
JShell – Métodos
Veamos cómo definir un método en JShell. En el siguiente ejemplo, hemos definido un método add()
y luego llamó a este método con argumentos para obtener la suma de dos enteros.
jshell> int add(int a, int b) { ...> return a+b; ...> } | created method add(int,int) jshell> add(10, 20) $2 ==> 30
JShell: cómo modificar la definición de un método ya definido
También podemos cambiar la definición de un método ya definido. En el siguiente ejemplo, estamos editando la definición del método. add()
jshell> int add(int a, int b) { ...> return a+b; ...> } | created method add(int,int) jshell> add(10, 20) $2 ==> 30 jshell> int add(int a, int b) { ...> return a+b+100; ...> } | modified method add(int,int) jshell> add(10, 20) $4 ==> 130
Nota: Dado que estamos cambiando la definición del método add (), los comentarios de JShell lo muestran como método modificado add (int, int) en vez de método creado add (int, int).