Is it possible to create Object for abstract class?

abstract class my {
    public void mymethod() {
        System.out.print("Abstract");
    }
}

class poly {
    public static void main(String a[]) {
        my m = new my() {};
        m.mymethod();
        System.out.println(m.getClass().getSuperclass());
    }
}

No, we can’t.The abstract super class is not instantiated by us but by java.

In the above code we are creating object for anonymous class.

my m = new my() {};

When the above code is compiled will result in following class file creation

My.class
Poly$1.class  // Class file corresponding to anonymous subclass
Poly.class

anonymous inner type allows you to create a no-name subclass of the abstract class

When the above code is run the output would be

Output

 Abstract
 class my

Now lets override the method in anonymous inner class like one below.

abstract class my {
    public void mymethod() {
        System.out.print("Abstract");
    }
}

class poly {
    public static void main(String a[]) {
        my m = new my() {
          public void mymethod() {
               System.out.print("Overridden in anonymous class");
           }
        };
        m.mymethod();
        System.out.println(m.getClass().getSuperclass());
    }
}

Output

 Overridden in anonymous class
 class my

Anonymous inner class with same name as abstract class are child classes of abstract class.

Comments are closed.