Signup/Sign In

Anonymous Inner Class Improvement

Java 9 added a new feature called type inference in an anonymous class. It allows us to leave empty diamond operator<> while creating an anonymous class.

It similarly appears like type inference in the collection framework. See improved type inference in the collection framework.

Let's have some examples to understand this feature in Java 9 and earlier versions.

Example: Java 8

In this example, we are creating an anonymous class that implements add() method to add integer type values. We executed this method using the Java 8 compiler. Since this feature was added to Java 9. So, the Java 8 compiler throws an error. See the example below.

interface Programable<T>{
	abstract T add(T t1, T t2);
}

public class Main { 
	public static void main(String[] args){
		Programable<Integer> p = new Programable<>() {
			public Integer add(Integer a, Integer b) {
				return a+b;
			}
		};
		Integer sum = p.add(10, 20);
		System.out.println(sum);
	}
}


Main.java:7: error: cannot infer type arguments for Programable<T>
Programable<Integer> p = new Programable<>() {
^
reason: cannot use '<>' with anonymous inner classes
where T is a type-variable:
T extends Object declared in interface Programable
1 error

Example: Java 9

If we execute this example using Java 9 then the compiler executes it fine and produces the desired result.

interface Programable<T>{
	abstract T add(T t1, T t2);
}

public class Main { 
	public static void main(String[] args){
		Programable<Integer> p = new Programable<>() {
			public Integer add(Integer a, Integer b) {
				return a+b;
			}
		};
		Integer sum = p.add(10, 20);
		System.out.println(sum);
	}
}


30

Example: Abstract Class

This example shows that if we have an abstract class then we can create an anonymous class from it and type inference works as well in this case.

abstract class Programable<T>{
	abstract T add(T t1, T t2);
}

public class Main { 
	public static void main(String[] args){
		Programable<Integer> p = new Programable<>() {
			public Integer add(Integer a, Integer b) {
				return a+b;
			}
		};
		Integer sum = p.add(10, 20);
		System.out.println(sum);
	}
}


30



About the author:
I am a Java developer by profession and Java content creator by passion. I have over 5 years of experience in Java development and content writing. I like writing about Java, related frameworks, Spring, Springboot, etc.