Can we instantiate abstract class?

Total Post:41

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

    Re: Can we instantiate abstract class?

    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:
    abstract class My {
        public void myMethod() {
    class Poly extends My {
        public static void main(String a[]) {
            My m = new My() {};
    Now, compile both your source files:

    Now in the directory where you compiled the source code, you will see the following class files:

    Poly$1.class  // Class file corresponding to anonymous subclass
    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.