What does the syntax mean in Java: new Stream(){ … }?

后端 未结 3 648
夕颜
夕颜 2021-01-20 23:30

I have encountered the following Java syntax that I don\'t recognize.

This part is fine:

public abstract class Stream implements Iterator

        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 00:01

    This is providing an inline (anonymous) subclass of the Stream class.

    Functionally, it is the same as:

    public NewClass extends Stream {
        public Integer next() {  
           return 1; 
        }  
    }
    

    and

    void someMethodInAnotherClass {
        Stream stream = new NewClass();
    }
    

    but as this class definition isn't used outside the method body, you can define it as anonymous.

提交回复
热议问题