2

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.

Vysakh Prem
  • 93
  • 1
  • 12
  • 2
    @Nambari: no, they can't. See http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29 – JB Nizet Dec 09 '12 at 13:46
  • @Nambari: I have an exact reference: the javadoc I linked to, which says: "Throws: InstantiationException - if this Class represents an abstract class" – JB Nizet Dec 09 '12 at 13:50
  • @JBNizet: This code works perfectly in eclipse. – Vysakh Prem Dec 09 '12 at 14:10
  • @VysakhPrem: No, no I am not saying it won't work. It should work. But the reason what I have in my mind is different. JB Nizet clarified that. – kosa Dec 09 '12 at 14:14

3 Answers3

6

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.

Mik378
  • 21,881
  • 15
  • 82
  • 180
4

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.

Community
  • 1
  • 1
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
1

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

Michael A
  • 5,770
  • 16
  • 75
  • 127