Java insists that all variables are declared in advance, with type information.
The compiler can then check whether the program is well-typed.
public class Employee { ... }
public class Manager extends Employee { ... }
Employee e;
Manager m;
...
m = new Manager();
e = m; // Possible due to subtyping.
An alternative approach is to do type inference.
<aside> 💡 Derive type information from the context.
</aside>
s = "Hello" + "World";
s
should be a String.t = s + 5;
t
is also String.This assumes that the code is well-typed to derive the most general types
To make it more ambitious, Look at the example below:
public class Employee() { ... }
public class Manager extends Employee {
...
public double bonus ( .. ) { ... }
}
...
public static f(Employee x){
double d = x.bonus();
...
}
x.bonus()
is legal, x
must be Manager
rather than Employee
→ More ambitious form of type inference.Typing judgements should ideally be made at compile-time, not run-time → Static Analysis of Code.
Java allows limited Type Inference.
<aside>
💡 Use generic var
to declare variables.
Must be initialized when declared.
</aside>
Type is inferred from initial value.
var b = false; // boolean
var s = "Hello" + "World"; // String
Be careful about format for numeric constants.
var d = 2.0; // double
var f = 3.14f; // float