Reputation: 544
I have read that in Java interfaces can't be instantiated (in the documentation, Interfaces). Runnable, by definition is an interface which should be implemented by some class. But in the following piece of code from one of my Android applications I see that an empty constructor - Runnable()...(I am not sure if it is a constructor) has been used, and an instance has been created - getStatus.
final Runnable getStatus = new Runnable()
{
public void run()
{
TextView uat = (TextView) findViewById(R.id.useAndThrow);
uat.setText(MyThread.getStatus());
return;
}
};
What I have come to know:
But I am not able to connect the dots. Assuming that the above code was inside the myActivity class, what is being instantiated and how is this anonymous class?
A bit of detail would be great.
Upvotes: 9
Views: 2566
Reputation: 115980
It's called an "anonymous class". Some notes about it:
You didn't provide it with a name, so one is created for you. In order to see what its real name is, simply write it to the console or read the bytecode.
The anonymous class, if created in the scope of the outer class, has a reference to its fields, just like any inner class. In general, it has the same scope of where it was created.
It's a very common thing to do if all you need is a simple implementation. The more code there is, the more you should consider putting it in a another file (for order, not because you can't).
Runnable is not the only interface that is common. On Android, you use OnClickListener, OnTouchListener, ...
Since the anonymous class has the same scope as to where it was declared, it means that it has a reference. Try to never keep an anonymous class for too long (for example, in a static reference) , since this could lead to memory leaks. On Android it's very crucial, as this sample shows (talks about drawables, but an anonymous class can also have a reference to a context) .
Some of the disadvantages of anonymous classes are that they don't have a constructor, and that it cannot implement more than one interface. It has a very narrow usage, yet it's very popular as it's very easy to use (and read).
Upvotes: 7
Reputation: 974
Google for more information on this using "Anonymous innerclass". This "Inner classes in Java, the mystery within" blog post explains quite well the different types of inner classes. See also "3.12. Anonymous Classes".
Upvotes: 2
Reputation: 2425
What is being instantiated is an anonymous subclass of Runnable
. It's called anonymous because the type itself does not have a name. In this subclass you are implementing the run()
method which is specified in the Runnable
interface.
The type of getStatus
is Runnable
, however the object that is being referenced by getStatus
is actually an implementation of Runnable
that does not have an explicit named type.
Upvotes: 1
Reputation: 4147
The code is creating an instance of a class which implements the Runnable interface. The class does not have a name.
Upvotes: 0