Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java new Interface instance syntax - what's happening?

Tags:

java

interface

What happens when you declare a new instance of an Interface as follows:

OnClickListener oc = new OnClickListener(){
    @Override
    public void onClick(View v){
         //Something
    }
};

Where is the method onClick stored? Its got to be in some sort of class storage? Does this mean that this syntax creates an unnamed class and implicitly implements the OnClickListener interface to it? If so, how come you can assign different OnClickListener objects to each other? Surely as they are 'implicitly' different class types, this assignment of two different classes is impossible.

Could someone explain?

like image 474
user965369 Avatar asked Jul 04 '26 10:07

user965369


1 Answers

It's called an Anonymous class.

If your code is in File Foo.java, and you compile it, you would get Foo.class and Foo$1.class for the first anonymous class. (Foo$2.class and so on for more anonymous classes).

like image 154
jlordo Avatar answered Jul 07 '26 00:07

jlordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!