Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java 9 Diamond Operator

Java 9 Diamond Operator

Java 9 New Features Java 9 New Features

The diamond operator was introduced in Java 7 to make code more readable, but it cannot be used with anonymous inner classes.

In Java 9, it can be used with anonymous inner classes, improving code readability.

Consider the following code from before Java 9:

Example

public

class

Tester

{

public

static

void

main

(

String

[

]

args

)

{

Handler

<

Integer

intHandler

=

new

Handler

<

Integer

(

1

)

{

@

Override

public

void

handle

(

)

{

System

.

out

.

println

(

content

)

;

}

}

;

intHandler

.

handle

(

)

;

Handler

intHandler1 = new Handler < Number > ( 2 ) { @ Override public void handle ( ) { System . out . println ( content ) ; } } ; intHandler1 . handle ( ) ; Handler

handler

=

new

Handler

<

Object

(

"

test

"

)

{

@

Override

public

void

handle

(

)

{

System

.

out

.

println

(

content

)

;

}

}

;

handler

.

handle

(

)

;

}

}

abstract

class

Handler

<

T

{

public

T

content

;

public

Handler

(

T

content

)

{

this

.

content

=

content

;

}

abstract

void

handle

(

)

;

}

The execution output is:

1

2

Test

In Java 9, we can use the <> operator in anonymous classes, as shown below:

Example

public

class

Tester

{

public

static

void

main

(

String

[

]

args

)

{

Handler

<

Integer

intHandler

=

new

Handler

<>

(

1

)

{

@

Override

public

void

handle

(

)

{

System

.

out

.

println

(

content

)

;

}

}

;

intHandler

.

handle

(

)

;

Handler

intHandler1 = new Handler <> ( 2 ) { @ Override public void handle ( ) { System . out . println ( content ) ; } } ; intHandler1 . handle ( ) ; Handler

handler

=

new

Handler

<>

(

"

test

"

)

{

@

Override

public

void

handle

(

)

{

System

.

out

.

println

(

content

)

;

}

}

;

handler

.

handle

(

)

;

}

}

abstract

class

Handler

<

T

{

public

T

content

;

public

Handler

(

T

content

)

{

this

.

content

=

content

;

}

abstract

void

handle

(

)

;

}

The execution output is:

1

2

Test

Java 9 New Features Java 9 New Features