Sub topic 8
Inferred Type Versus Declared Type
This chapter assumes that you understand Java reference types, inheritance, interfaces, and generic collections. The key distinction is between a variable's static type and the object's runtime type.
A static type is the type the compiler uses when checking method calls and assignments. A runtime type is the class of the object that exists while the program runs. The var declaration changes how the static type is written, but it does not remove static typing.
The type selected by `var`
With an explicit declaration, you choose the variable's static type:
Shape shape = new Circle();The variable has static type Shape, even though the object is a Circle. You can call only methods declared by Shape through shape.
With var, the compiler uses the compile-time type of the initializer:
var circle = new Circle();Here, circle has static type Circle. The compiler inferred the type from the expression new Circle().
The inferred type is not always the object's most specific runtime class. It is the type produced by the initializer expression:
var shape = createShape();If createShape() is declared to return Shape, then shape has static type Shape, even if the method returns a Circle object at runtime.
| Declaration | Static type | Methods available through the variable |
|---|---|---|
| `Shape a = new Circle()` | `Shape` | Methods declared by `Shape` |
| `var b = new Circle()` | `Circle` | Methods declared by `Circle` |
| `var c = createShape()` | Return type of `createShape` | Methods declared by that return type |
Polymorphism and API boundaries
Explicit types are useful when you want to program against an abstraction. An interface or superclass can limit the operations used by a variable and make the intended contract clear.
import java.util.ArrayList;
import java.util.List;
public class TypeChoice {
static List<String> names() {
return new ArrayList<>(List.of("Ada", "Linus"));
}
public static void main(String[] args) {
List<String> declared = names();
var inferred = new ArrayList<String>();
System.out.println(declared.size());
inferred.ensureCapacity(10);
// declared.ensureCapacity(10); // List has no such method
}
}The variable declared has static type List<String>, because that is the method's return type. The variable inferred has static type ArrayList<String>, because the initializer explicitly constructs an ArrayList<String>.
This difference affects later refactoring. If the implementation changes from ArrayList to another List implementation, an explicit interface type often keeps the rest of the code independent of that implementation. Using var can expose implementation-specific methods and make that dependency less obvious.
Anonymous classes and types without a name
Some inferred types cannot be written directly as ordinary Java type names. An anonymous class is one example:
public class AnonymousType {
public static void main(String[] args) {
var counter = new Object() {
int value = 7;
int next() {
return ++value;
}
};
System.out.println(counter.next()); // 8
System.out.println(counter.value); // 8
}
}The compiler gives counter the anonymous class's type. That type has no source-level name, but var can still refer to it. If the variable were declared as Object, neither next() nor value would be available through the variable.
Choosing between `var` and an explicit type
Use var when the initializer makes the type obvious or when the type is difficult or impossible to write:
var user = new User(id);var entries = new ArrayList<Map.Entry<String, Integer>>();var result = createConfiguredAnonymousObject();
Use an explicit type when the abstraction communicates an important design decision:
List<String> names = loadNames();CharSequence text = readText();Number value = calculateValue();
A useful test is to read the declaration without inspecting several lines below it. If the reader cannot reasonably identify the type or the intended abstraction, an explicit type may be clearer.
Exercise
A method static Shape makeShape() returns a Circle object. What is the static type of var shape = makeShape(), and why?
Show answer
The static type is Shape, because var uses the method expression's declared return type. The runtime object may still be a Circle.