Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 67 java 10 Type Inference with Nondenotable Types Java has several nondenotable types that is types that can exist within your program but for which theres no way to explicitly write out the name for the types A good example of a nondenotable type is an anonymous class you can add fields and methods to it but you wont be able to write the name of the anonymous class in your Java code The diamond operator cant be used with anonymous classes var is less restricted and can be used to support some nondenotable types specifically anonymous classes and intersection types The var keyword also enables you to use anonymous classes more efectively and refer to types that would otherwise be impossible to describe Normally if you create an anonymous class you can add fields to it but you cant refer to those fields elsewhere because they need to be assigned back to a named type For example the following code wont compile because the type of productInfo is an Object and you cant access fields name and total of an Object Object productInfo new Object String name Apple int total 30 System out println name productInfo name total productInfo total With var you can overcome this limitation When you assign an anonymous class to a var typed local variable the compiler infers the type of the anonymous class rather than the type of its parent This means that you can refer to fields declared in the anonymous class as illustrated in the following code var productInfo new Object String name Apple int total 30
You must have JavaScript enabled to view digital editions.