Vysakh Prem
Vysakh Prem

Reputation: 93

Creating instance of static abstract class

I know that abstract classes cannot be instantiated. But I have a doubt in the code below. This code is a part of android bitmap fun demo ( http://commondatastorage.googleapis.com/androiddevelopers/shareables/training/BitmapFun.zip).

// ImageWorkerAdapter class is nested in another abstract class ImageWorker
public static abstract class ImageWorkerAdapter
{
public abstract Object getItem(int num);
public abstract int getSize();
}

//this snippet is seen in Images.java
public final static ImageWorkerAdapter imageWorkerUrlsAdapter = new ImageWorkerAdapter() { 
@Override
public Object getItem(int num) {
return Images.imageUrls[num];
}

I cannot understand how it is possible to create an instance of an abstract class. Please help me to understand this code.

Upvotes: 2

Views: 666

Answers (3)

Michael A
Michael A

Reputation: 5840

Your code does not instantiate an abstract class, but defines new anonymous abstract class which among others extends and implement (override) other abstract class.

Upvotes: 1

Pete Kirkham
Pete Kirkham

Reputation: 49321

The code you show does not show an abstract class being instantiated.

It shows an anonymous class being instantiated. In this case, the anonymous class extends an abstract class. You can also implement interfaces in anonymous classes, Runnable being a very common example.

Upvotes: 4

Mik378
Mik378

Reputation: 22191

This code represents the initialization of an anonymous class extending ImageWorkerAdapter abstract class:

new ImageWorkerAdapter() { 
    @Override
    public Object getItem(int num) {
    return Images.imageUrls[num];
}

Indeed, the anonymous implementation is defined between the curly braces.

As being an anonymous class, it's perfectly valid to rely on an abstract class or interface.

Upvotes: 6

Related Questions