With Java 10 or +, we can use var keyword for declaration. At initialization, a type is going to be inferred by the compiler.
What happens when the class I instantiate and assign to the variable declared with var
, is the implementation of the interface? which type is it going to be inferred, Interface or the implementation?
My 2 cents to correct the question and answers:
var
is NOT a Java keyword. It's a reserved type name. It seems not a big difference but in fact, it IS:var var = 0;
Here var
is a variable name too, so the var
can be used as a type name, but there is no restriction like for regular keyword (i.e. we can have a variable named var
too).
var i = true ? Integer.valueOf(1) : "ABC";
The Java compiler needs to pick a type for variable i
which will satisfy both branches. It could be a) Object
, b) Serializable
, c) Comparable
, or combinatioin, or all three. We don't care and don't know.
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