What does the syntax mean in Java: new Stream <Integer> () {...}?
I came across the following Java syntax, which I do not know.
This part is in order:
public abstract class Stream<T> implements Iterator<T> {
public boolean hasNext() {
return true; }
public void remove() {
throw new RuntimeException("Unsupported Operation"); }
}
But this I do not get:
Stream<Integer> ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};
while(true){
System.out.print(ones.next() + ", ");
}
What it is?
+3
3 answers
This provides a built-in (anonymous) subclass of the class Stream.
Functionally, this is the same as:
public NewClass extends Stream {
public Integer next() {
return 1;
}
}
and
void someMethodInAnotherClass {
Stream stream = new NewClass();
}
but since this class definition is not used outside the method body, you can define it as anonymous.
+4