This may be a very elementary question for Java, but I just can’t recall it and have no clue how to search it online.
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Thread.sleep(100);
}
}
I’m used to initializing an object using constructors like new OnClickListener(arg1, arg2, ...). In my own experience I’ve never override a method when constructing an object. I’ve only done it when extending a class. What is this kind of instantiation called in Java if there’s any term for it? In what other cases should we use it?
That’s an anonymous class. It’s an implementation of the
OnClickListenerinterface, but that implementation is unnamed. It’s concise to write and the implementation is visible in the calling context (often useful for readability), but since it’s an implementation in-place, you can’t use it elsewhere.Note also that it’s an inner class and hence has a reference to its surrounding class.
See here for more info.
Re. the reference to a surrounding class. An inner class has an implicit reference to its outer class (you can see this if you attempt to serialise the inner class using, say, XStream. It’ll pull the outer class along with it). If you have a variable in the outer class, you can reference it in the inner (provided it’s a
finalvariable, mind)