Sub topic 8
Declaring classes, records and interfaces
This chapter covers how JShell handles type declarations, what happens when you redefine a type, and which Java rules JShell relaxes. It assumes you can write classes, records and interfaces in compiled Java and that you know the snippet model from earlier chapters. Records need JDK 16 or later. The examples use JDK 21.
Types are snippets too
A class, record, interface or enum declaration is one snippet, like a variable or a method. You don't need a file, a main method, or an enclosing class. JShell reads the declaration, compiles it, and reports created.
Multi-line declarations work because JShell detects incomplete input. It shows a continuation prompt until the braces balance.
jshell> class Counter {
...> private int count;
...> void increment() { count++; }
...> int get() { return count; }
...> }
| created class Counter
jshell> Counter c = new Counter()
c ==> Counter@1b6d3586
jshell> c.increment()
jshell> c.get()
$4 ==> 1The hash after Counter@ will differ on your machine. The call to c.increment() prints nothing because the method returns void.
Records and interfaces
Records are convenient in JShell because the compiler generates toString, equals and accessors. A short record gives readable output immediately.
jshell> record Point(int x, int y) {
...> double distanceTo(Point other) { return Math.hypot(x - other.x, y - other.y); }
...> }
| created record Point
jshell> var p = new Point(3, 4)
p ==> Point[x=3, y=4]
jshell> p.distanceTo(new Point(0, 0))
$3 ==> 5.0Interfaces work the same way. You can implement one with a record, a class, or a lambda if it is a functional interface.
jshell> interface Shape { double area(); default String describe() { return "area=" + area(); } }
| created interface Shape
jshell> record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }
| created record Circle
jshell> new Circle(1).describe()
$3 ==> "area=3.141592653589793"
jshell> Shape unit = () -> 1.0
unit ==> $Lambda/0x000001a2b3c04000@4b1210ee
jshell> unit.describe()
$5 ==> "area=1.0"The public on area() in Circle is still required. Methods that implement interface methods follow normal Java rules. The lambda's printed name will differ between runs and JDK versions.
Redefining a type
You can declare a type again under the same name. This is the main difference from compiled Java, where a duplicate class is an error. What JShell does next depends on the change:
- If the JVM can swap the new definition in place, JShell reports
modified. This works for changes such as a new method body. Existing instances stay alive and use the new code. - If the change alters the shape of the class, JShell reports
replaced. Adding a field or changing a signature does this. Variables holding the old type are reset tonull, because the old objects no longer match the class.
Here is both outcomes with the Counter from earlier. The variable c holds a count of 1.
jshell> class Counter {
...> private int count;
...> void increment() { count += 2; }
...> int get() { return count; }
...> }
| modified class Counter
jshell> c.increment()
jshell> c.get()
$7 ==> 3
jshell> class Counter {
...> private int count;
...> private String label;
...> void increment() { count += 2; }
...> int get() { return count; }
...> }
| replaced class Counter
| update replaced variable c, reset to null
jshell> c
c ==> nullThe first change kept the count of 1 and the second call added 2. The second change discarded c. This reset is the usual surprise when you experiment with a type. After a replaced message, check /vars and recreate any objects you still need.
Other snippets that mention the type are recompiled automatically. A method that takes a Counter parameter is updated, and you will see an update line for it.
Modifiers that JShell ignores
Snippets are not members of a user-written class, so some modifiers don't apply at the top level. If you write public class Box { }, JShell prints a warning that the modifier public is not permitted in top-level declarations and ignored. It then creates the class anyway. The same applies to private, protected and static.
Nested types inside a declaration keep all their normal modifiers. A private static class Node inside your own class behaves as it would in a compiled file.
jshell> class LinkedStack {
...> private static class Node { int value; Node next; Node(int v, Node n) { value = v; next = n; } }
...> private Node top;
...> void push(int v) { top = new Node(v, top); }
...> int pop() { int v = top.value; top = top.next; return v; }
...> }
| created class LinkedStack
jshell> var s = new LinkedStack()
s ==> LinkedStack@3cd1a2f1
jshell> s.push(1); s.push(2); s.pop()
$4 ==> 2Several snippets can go on one line. JShell splits them and evaluates each in turn. Only the last expression produces a scratch variable here, because push returns void.
Inspecting and removing types
The /types command lists the classes, interfaces, enums and records in the session. /drop removes one by name.
jshell> /types
| class Counter
| record Point
| interface Shape
| record Circle
| class LinkedStack
jshell> /drop Shape
| dropped interface Shape
| update replaced class Circle, however, it cannot be instantiated or its methods invoked until interface Shape is declaredDropping Shape leaves Circle in an unresolved state. Circle implements Shape, so it cannot be used until you declare Shape again. The next chapter covers this state. For now, remember that /drop has effects on dependent types.
Differences from compiled Java
- A type name can be declared twice. The newest declaration wins.
public,private,protectedandstaticare ignored on top-level types.- The compiled class name is wrapped in a synthetic scope, so
getClass().getName()returns a generated name instead of justCounter. Don't rely on it. - There is no
packagestatement. Types belong to the session's own scope. - Type declarations can refer to types that don't exist yet, as long as you declare them before use.
Exercise
In a fresh session you declare record Pair(int a, int b) {} and then var q = new Pair(1, 2). You then declare record Pair(int a, int b, int c) {}. What does JShell report, and what is the value of q afterwards?
Show answer
Adding a record component changes the class's shape, so the JVM cannot redefine it in place. JShell reports replaced record Pair and updates q with the message update replaced variable q, reset to null. Entering q afterwards prints q ==> null. You must create a new Pair with three arguments.
Exercise
You declare class Greeter { String hi() { return "hi"; } }, create var g = new Greeter(), and then declare Greeter again with the body of hi() changed to return "hello". Does g.hi() return "hello" without recreating g? Why?
Show answer
Yes. Changing only a method body is a change the JVM can apply in place, so JShell reports modified class Greeter and keeps g. The existing object runs the new code, so g.hi() returns "hello".