Type inference
is a feature of Java that was introduced in Java 7. Now, Java compiler can infer type of a data automatically.
For example, if we create an ArrayList then we use the code like:
1 2 3 4 |
List<String> list = new ArrayList<String>(); // Before Java 7 List<String> list = new ArrayList<>(); // From Java 7 and onward |
You can see that Java 7
allows us to use empty diamond operator to avoid code redundancy. But we can use this Java collection only, what about the anonymous class?
If we do the same in Java 7 with anonymous class, means use empty diamond(<>)
in an anonymous class then compiler reports an error. See the example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
abstract class CalculateAble<T>{ abstract T add(T a, T b); } public class Main { public static void main(String[] args) { CalculateAble<Integer> a = new CalculateAble<>() { // diamond operator is empty public Integer add(Integer a, Integer b){ return a+b; } }; int result = a.add(10, 20); System.out.println(result); } } |
Output
CalculateAble a = new CalculateAble() {
^
reason: cannot use ” with anonymous inner classes
Note: The empty diamond operator with anonymous classes was not allowed in Java SE 7.
This is how we create an anonymous class
in Java. It works fine with all the Java versions.
1 2 3 4 5 6 7 |
DemoCalculator<Integer> a = new DemoCalculator<Integer>() { // diamond operator is not empty Integer show(Integer a, Integer b){ return a+b; } }; |
Anonymous class: Java 9 Improvement
Java improved its type inference feature and allowed us to use (diamond) in the anonymous class too. For example, if we create an anonymous class with empty diamond(<>)
, then the compiler does not report any error and will compile the code successfully.
Example: Anonymous class with diamond operator
Let’s execute this example using Java 9
and higher version and see. It will execute fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
abstract class CalculateAble<T>{ abstract T add(T a, T b); } public class Main { public static void main(String[] args) { CalculateAble<Integer> a = new CalculateAble<>() { // diamond operator is empty public Integer add(Integer a, Integer b){ return a+b; } }; int result = a.add(10, 20); System.out.println(result); } } |
Output
Well, this is all about the use of diamond operator in an anonymous class in Java 9 version.