Java 9 Diamond Operator for Anonymous Inner Classes

java-9-diamond-operator-anonymous-inner-class-feature-image

Java 7 has a new feature called Diamond Operator which helps to make code more readable, but it is still limited with Anonymous Inner Classes. In this article, we will introduce Java 9 Diamond Operator that can simplifies code and improves readability.

1. Diamond Operator Problem with Anonymous Inner Classes

Assume that we have MyHandler class:

public abstract class MyHandler {

	// constructor, getter, setter...

	abstract void handle();
}

With Java 8, we can write code like this for Anonymous Class:

		MyHandler intHandler = new MyHandler(1) {

			public void handle() {
				// handling code...
			}
		};

But how about the cases with Diamond Operator as below:

MyHandler intHandler = new MyHandler<>(10) { // Anonymous Class };
MyHandler handler = new MyHandler<>(""One hundred") { // Anonymous Class };

We get the compile error: ‘<>‘ cannot be used with anonymous classes.

2. Java 9 Diamond Operator Improvement

Java 9 allows the Diamond Operator for Anonymous Inner Classes. Now we can write code easily without compile error:

		MyHandler intHandler = new MyHandler<>(1) {

			@Override
			public void handle() {
				// handling code...
			}
		};

		MyHandler intHandler1 = new MyHandler<>(10) {

			@Override
			void handle() {
				// handling code...
			}
		};
		
		MyHandler handler = new MyHandler<>("One hundred") {

			@Override
			void handle() {
				// handling code...
			}
		};
	}
SOURCE CODE

MyHandler.java

package com.javasampleapproach.jv9diamondoperator;

public abstract class MyHandler {

	private T content;

	public MyHandler(T content) {
		this.content = content;
		System.out.println("constructor for MyHandler with content: " + content.toString());
	}

	public T getContent() {
		return content;
	}

	public void setContent(T content) {
		this.content = content;
	}

	abstract void handle();
}

MainApp.java

package com.javasampleapproach.jv9diamondoperator;

public class MainApp {

	public static void main(String[] args) {

		MyHandler intHandler = new MyHandler<>(1) {

			@Override
			public void handle() {
				System.out.println("handle > " + getContent());
			}
		};

		intHandler.handle();

		MyHandler intHandler1 = new MyHandler<>(10) {

			@Override
			void handle() {
				System.out.println("handle > " + getContent());
			}
		};

		intHandler1.handle();

		MyHandler handler = new MyHandler<>("One hundred") {

			@Override
			void handle() {
				System.out.println("handle > " + getContent());
			}
		};

		handler.handle();
	}
}

Run code, the result shows:

constructor for MyHandler with content: 1
handle > 1
constructor for MyHandler with content: 10
handle > 10
constructor for MyHandler with content: One hundred
handle > One hundred


By grokonez | March 26, 2017.

Last updated on September 11, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*