Sub topic 12
Non-denotable types and anonymous classes
This chapter assumes you know how var infers a type from its initializer, that the variable keeps a fixed static type, and how anonymous classes are declared. It covers the types that only var can hold, and the limits of using them.
What "denotable" means
A type is denotable if you can write it as a name in source code. int, String, List<String> and Map<String, Integer> are all denotable. A non-denotable type exists inside the compiler, but no source text can name it.
Before Java 10, a non-denotable type could only appear as an intermediate result. You could call a method on it, but you could not store it in a variable without widening it to something you could name. var removes that restriction. The variable gets the exact type of the initializer, whether or not you could have written that type.
Three kinds of non-denotable types matter in practice:
| Kind | Example source | What `var` does with it |
|---|---|---|
| Anonymous class type | `new Object() { int x; }` | Keeps the exact anonymous type, so its members are accessible |
| Intersection type | `(Runnable & Serializable) () -> {}` | Keeps the intersection, so members of every component type are accessible |
| Capture type | A value read from a `List<? extends Number>` | Replaced by a nameable type (the upward projection) |
Anonymous classes with var
An anonymous class creation expression has a type: a new, unnamed subclass of the class or interface you wrote after new. When you declare the variable with Object, you throw that type away and keep only Object. When you declare it with var, you keep it.
public class VarAnonymous {
public static void main(String[] args) {
var point = new Object() {
int x = 3;
int y = 4;
};
System.out.println(point.x + point.y); // 7
Object widened = new Object() {
int x = 3;
};
// System.out.println(widened.x); // does not compile: Object has no field x
}
}The compiler generates a class for the anonymous body, named something like VarAnonymous$1. The type of point is that class. Fields, methods and nested state declared in the body are all visible through the variable.
This also works for members that are not fields. A one-off local object with state and behavior is a typical use:
public class VarAnonymousState {
public static void main(String[] args) {
var counter = new Object() {
int hits = 0;
void hit() { hits++; }
};
for (var i = 0; i < 3; i++) {
counter.hit();
}
System.out.println(counter.hits); // 3
}
}The type is unique to that expression
Each anonymous class expression creates its own type, even when the bodies look identical. That has a consequence for reassignment:
public class VarAnonymousReassign {
public static void main(String[] args) {
var p = new Object() { int x = 1; };
p.x = 2; // fine
// p = new Object() { int x = 5; }; // does not compile: a different anonymous type
System.out.println(p.x); // 2
}
}Assigning a second anonymous class instance to p fails because the two classes are unrelated apart from both extending Object. You can still assign null, but you cannot assign any other expression that does not have the same type.
Anonymous types survive generic inference
The anonymous type also flows through generic methods, because a type variable can be inferred as any type, denotable or not.
import java.util.stream.Stream;
public class VarAnonymousStream {
static <T> T identity(T value) { return value; }
public static void main(String[] args) {
var point = new Object() { int x = 3; };
var same = identity(point);
System.out.println(same.x); // 3
Stream.of("ada", "grace", "linus")
.map(n -> new Object() { String name = n; int len = n.length(); })
.filter(p -> p.len > 3)
.forEach(p -> System.out.println(p.name)); // grace, then linus
}
}In the stream pipeline, map infers its result type R as the anonymous class. The lambdas in filter and forEach then receive that type, so p.len and p.name resolve. No var appears in that pipeline at all. The inference mechanism is the same one var relies on.
Where the anonymous type stops
You can keep the anonymous type only as long as the compiler can see the expression's type. It cannot cross a boundary where you must write a type name:
- A method parameter cannot be declared with an anonymous type, because there is no name to write.
- A method return type cannot be the anonymous type. If you return the object, the declared return type (
Objector an interface) is all callers see. - A field cannot use
var, so a field holding the object also loses the extra members.
A generic helper like identity is the exception, because the type variable is inferred at each call site.
An anonymous class that extends a class or implements an interface works the same way. var task = new Runnable() { int runs; public void run() { runs++; } }; gives you task.runs as well as task.run(). Declaring it as Runnable task would hide runs.
Intersection types
An intersection type is a type that is a subtype of several types at once, written A & B in generic bounds and casts. You cannot declare a variable with one, but var can hold one.
import java.io.Serializable;
import java.util.List;
public class VarIntersection {
public static void main(String[] args) {
var task = (Runnable & Serializable) () -> System.out.println("running");
task.run(); // from Runnable
Serializable saved = task; // also a Serializable
System.out.println(saved != null); // true
var mixed = List.of(1, "two"); // element type is the lub of Integer and String
Serializable first = mixed.get(0); // the element type includes Serializable
System.out.println(first); // 1
}
}The second case shows an intersection you did not write. List.of(1, "two") needs a type that both Integer and String extend. The compiler computes their least upper bound, which is Object plus several shared interfaces such as Serializable and Comparable. The exact list of interfaces depends on the Java version, so rely only on interfaces you know both types implement.
Capture types are projected away
A wildcard such as List<? extends Number> has no single element type. When you read from it, the compiler gives the value a fresh capture type, an anonymous stand-in that is known only to be a Number. Capture types are non-denotable too, but var does not keep them. The language rule is that the variable gets the upward projection of the initializer type, which replaces capture types with their bounds.
import java.util.List;
public class VarCapture {
public static void main(String[] args) {
List<? extends Number> nums = List.of(1, 2.5);
var n = nums.get(0); // Number, not a capture type
System.out.println(n.doubleValue()); // 1.0
}
}This is why the anonymous-class and intersection cases are special. The language deliberately keeps those two, because they carry members you wrote, and drops capture types, which only describe a limitation of wildcards.
Why you might not want this
Anonymous types are legal and compile-time safe, but they are an unusual style. Before using one, consider these points:
- A local record is usually clearer. Since Java 16 you can declare
record Point(int x, int y) {}inside a method. It has a name, a constructor,equals,hashCodeandtoString, and it can be passed to other methods. - Anonymous classes capture context. In an instance method, an anonymous class holds a reference to the enclosing
this. Keeping the object alive keeps the outer object alive. - No generated
toStringorequals. Printing the object shows something likeVarAnonymous$1@1b6d3586. - Readers may not expect it. A reviewer who sees
point.xaftervar point = new Object() {...}has to know the trick.
A reasonable rule: use the anonymous var form for a short-lived, single-method grouping of a few values, and switch to a local record as soon as the shape is used in more than a couple of places or needs methods like equals.
Exercise
Why does Object o = new Object() { int x = 3; }; followed by o.x fail to compile, while var o = new Object() { int x = 3; }; followed by o.x compiles?
Show answer
A variable's static type decides which members you can access. With Object o, the static type is Object, which has no field x. With var, the static type is the anonymous class created by the expression, and that class declares x.
Exercise
Given var p = new Object() { int x = 1; };, why does p = new Object() { int x = 2; }; fail, and what would make the second assignment legal?
Show answer
Each anonymous class expression creates its own distinct class, so the second expression's type is not the type of p. The assignment becomes legal if both values share a named type, for example by declaring a local record or class and using var p = new Point(1); followed by p = new Point(2);.
Exercise
What static type does n have in List<? extends Number> nums = List.of(1, 2.5); var n = nums.get(0);, and why is it not the capture type?
Show answer
n has type Number. The expression's type is a capture type, but var replaces capture types with their upward projection, which here is the bound Number.