Home > DeveloperSection > Forums > Can we instantiate abstract class?
Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    July-24-2015 11:27 PM

 Java Java  Abstract Class 
Ratings:


 1 Reply(s)
 442  View(s)
Rate this:
abstract class my {
    public void mymethod() {
        System.out.print("Abstract");
    }
}
class poly {
    public static void main(String a[]) {
        my m = new my() {};
        m.mymethod();
    }
}
Here, I'm creating instance of my class and calling method of abstract class. Can anyone please explain this to me? 


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-25-2015 7:57 AM

No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.

To practically see that the class being instantiated is an Anonymous SubClass, you just need to compile both your classes. Suppose you put those classes in two different files:

My.java:
abstract class My {
    public void myMethod() {
        System.out.print("Abstract");
    }
}
Poly.java:
class Poly extends My {
    public static void main(String a[]) {
        My m = new My() {};
        m.myMethod();
    }
}
Now, compile both your source files:

javac My.java Poly.java
Now in the directory where you compiled the source code, you will see the following class files:

My.class
Poly$1.class  // Class file corresponding to anonymous subclass
Poly.class
See that class - Poly$1.class. It's the class file created by the compiler corresponding to the anonymous subclass you instantiated using the below code:
new My() {};
So, it's clear that there is a different class being instantiated. It's just that, that class is given a name only after compilation by the compiler.

In general, all the anonymous subclasses in your class will be named in this fashion:

Poly$1.class, Poly$2.class, Poly$3.class, ... so on
Those numbers denote the order in which those anonymous classes appear in the enclosing class.

Don't want to miss updates? Please click the below button!

Follow MindStick