I was just playing around with JShell, and it seems that defining class Z{}
and then defining
var z = new Z()
does not work. But using different class names, like class X
and class A
, does work.
Surely I must be missing something obvious...?
| Welcome to JShell -- Version 14.0.1
| For an introduction type: /help intro
jshell> class X{}
| created class X
jshell> class Z{}
| created class Z
jshell> var x = new X()
x ==> X@26a1ab54
| created variable x : X
jshell> var z = new Z()
| Error:
| unexpected type
| required: class
| found: type parameter Z
| var z = new Z();
| ^
jshell> class A{}
| created class A
jshell> var a = new A()
a ==> A@2ef1e4fa
| created variable a : A
Use of var
can lead to a variable having a non-denotable type. For example, looking at the return type of an expression that could be String
or Integer
:
jshell> /set feedback verbose
jshell> var x = true ? "a" : 1
x ==> "a"
| created variable x : Serializable&Comparable<? extends Serializable&Comparable<?>&java.lang.constant.Constable&java.lang.constant.ConstantDesc>&java.lang.constant.Constable&java.lang.constant.ConstantDesc
When jshell
is evaluating your code fragment, if this is the case, it wraps it in a block of code so that it can record this type for later use. The wrapping fragment includes a generic type parameter called Z
:
// private static <Z> Z do_itAux() {
// wtype x_ = y;
// @SuppressWarnings("unchecked")
// Z x__ = (Z) x_;
// return x__;
This parameter's name leaks into the code block being evaluated, meaning the class's name is shadowed by the type parameter. This makes Z
a special case -- the other single character examples are fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With