Searching...
Monday, March 19, 2018

Diamond Operator - Java9

March 19, 2018

// before Java 7, explicit generic type declaration required
List<String> myList = new ArrayList<String>();

// since Java 7, diamond operator can be used
List<String> list = new ArrayList<>();

  • Java 7 Diamond Operator was not possible for anonymous inner classes. 
  • Since Java 9, diamond operator can be used in anonymous inner classes

Simple Example

DiamondOperatorMain.java
 
package com.java9r;

/**
* @author Ravi
*
*/
public class DiamondOperatorMain {

/**
* @param args
*/
public static void main(String[] args) {

DiamondOperator<Integer> diamond = new DiamondOperator<>() {

public void testMethod() {
System.out.println("Test Method");
}
};
diamond.testMethod();

}
}

DiamondOperator.java
 package com.java9r;

/**
* @author Ravi
*
*/
public interface DiamondOperator<T> {
void testMethod();

}

Output
Test Method

Diamond Operator Using Abstract class Example

DiamondOperatorAbstractMain.java
 package com.java9r;

/**
* @author Ravi
*
*/
public class DiamondOperatorAbstractMain {

/**
* @param args
*/
public static void main(String[] args) {

DiamondOperatorAbstract<Integer> diamondOperator1 = new DiamondOperatorAbstract<>(1) { // Anonymous Class

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

DiamondOperatorAbstract<? extends Integer> diamondOperator2 = new DiamondOperatorAbstract<>(3) { // Anonymous Class

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

DiamondOperatorAbstract<?> diamondOperator3 = new DiamondOperatorAbstract<>("Three") { // Anonymous Class

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

}
}


DiamondOperatorAbstract.java
 package com.java9r;

/**
* @author Ravi
*
*/
public abstract class DiamondOperatorAbstract<T> {
private T content;

public DiamondOperatorAbstract(T content) {
this.content = content;
System.out.println("Constructor for Diamond Operator Abstract : " + content.toString());
}

public T getContent() {
return content;
}

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

abstract void handle();

}

Output
Constructor for Diamond Operator Abstract : 1
diamondOperator 1 > 1
Constructor for Diamond Operator Abstract : 3
diamondOperator 2 > 3
Constructor for Diamond Operator Abstract : Three
diamondOperator 3 > Three



1 comments:

  1. We hope that this web page has given you all of the answers about enjoying in} online roulette, however in case you have any questions at all, be at liberty to get in touch! We have tried to answer the most frequently requested questions beneath tons of|to keep 카지노 사이트 away from wasting} you from typing. You will discover plenty of websites online promising could be} a|that there's a} sure-fire system to beat roulette.

    ReplyDelete

ads2