I have encountered the following Java syntax that I don't recognize.
This part is fine:
public abstract class Stream<T> implements Iterator<T> {
public boolean hasNext() {
return true; }
public void remove() {
throw new RuntimeException("Unsupported Operation"); }
}
But this I don't get:
Stream<Integer> ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
while(true){
System.out.print(ones.next() + ", ");
}
What it is?
This is providing an inline (anonymous) subclass of the
Stream
class.Functionally, it is the same as:
and
but as this class definition isn't used outside the method body, you can define it as anonymous.
ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
Assigns a new instance of an anonymous implementation of
Stream<Integer>
(that contains a virtually unlimited number of1
s. You may find more on anonymous classes in Java In A NutshellThis is defining a Anonymous class which implements the Stream interface. To implement the interface we need to implement the method next.