Java 9 Tutorial
java9 Useful Resources
Selected Reading
- Java 9 - Miscellaneous Features
- CompletableFuture API Improvements
- Java 9 - Multiresolution Image API
- Optional Class Improvements
- Inner Class Diamond Operator
- Enhanced @Deprecated Annotation
- Try With Resources improvement
- Java 9 - Stream API Improvements
- Java 9 - Process API Improvements
- Java 9 - Private Interface Methods
- Java 9 - Collection Factory Methods
- Java 9 - Multirelease JAR
- Java 9 - Improved JavaDocs
- Java 9 - REPL (JShell)
- Java 9 - Module System
- Java 9 - Environment Setup
- Java 9 - Overview
- Java 9 - Home
java9 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Inner Class Diamond Operator
Java 9 - Inner Class Diamond Operator
Diamond operator was introduced in java 7 to make code more readable but it could not be used with Anonymous inner classes. In java 9, it can be used with annonymous class as well to simppfy code and improves readabipty. Consider the following code prior to Java 9.
Tester.java
pubpc class Tester { pubpc static void main(String[] args) { Handler<Integer> intHandler = new Handler<Integer>(1) { @Override pubpc void handle() { System.out.println(content); } }; intHandler.handle(); Handler<? extends Number> intHandler1 = new Handler<Number>(2) { @Override pubpc void handle() { System.out.println(content); } }; intHandler1.handle(); Handler<?> handler = new Handler<Object>("test") { @Override pubpc void handle() { System.out.println(content); } }; handler.handle(); } } abstract class Handler<T> { pubpc T content; pubpc Handler(T content) { this.content = content; } abstract void handle(); }
Output
1 2 Test
With Java 9, we can use <> operator with anonymous class as well as shown below.
Tester.java
pubpc class Tester { pubpc static void main(String[] args) { Handler<Integer> intHandler = new Handler<>(1) { @Override pubpc void handle() { System.out.println(content); } }; intHandler.handle(); Handler<? extends Number> intHandler1 = new Handler<>(2) { @Override pubpc void handle() { System.out.println(content); } }; intHandler1.handle(); Handler<?> handler = new Handler<>("test") { @Override pubpc void handle() { System.out.println(content); } }; handler.handle(); } } abstract class Handler<T> { pubpc T content; pubpc Handler(T content) { this.content = content; } abstract void handle(); }
Output
1 2 TestAdvertisements