Sunday 28 February 2016

Can we instantiate abstract class?

No, we cannot instantiate the abstract class. Because it's abstract and an object is concrete.

An abstract class is sort of like a template, or an empty/partially empty structure, we have to extend it and build on it before we can use it.


abstract class AbstractClass {
    public void method() {
        System.out.print("Abstract class method!!");
    }
}


There is compile time error while instantiating the abstract class.


public class  InstantiateAbstract {
     public static void main(String[] args) {
        AbstractClass object = new AbstractClass();
        object.method();
     }
}
Compile time error: Cannot instantiate the type AbstractClass


Now program is executing without any error.


public class  InstantiateAbstract {
     public static void main(String[] args) {
        AbstractClass object = new AbstractClass() {};
        object.method();
     }
}

Output:
Abstract class method!!


There is some difference to notice?
new AbstractClass() vs. new AbstractClass (){ };;

In the second case, extra curly braces are there, which is the body of a new, nameless class (anonymous class) that extends the abstract class. You have created an instance of an anonymous class and not of an abstract class.

Important point:

If there is any abstract method in abstract class, it is compulsory to provide the implementation of the abstract method inside the curly braces i.e. Compiler will force you to implement the abstract method inside {} of anonymous class.

References:
https://en.wikipedia.org/wiki/Abstract_type
https://en.wikipedia.org/wiki/Class_(computer_programming)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...