Home >Java >javaTutorial >Can We Instantiate an Abstract Class in Java?
Can We Instantiate an Abstract Class: A Deeper Dive
In conventional understanding, abstract classes cannot be instantiated. But a recent interview puzzle brought forth a different perspective. Let's delve into this intriguing question with a practical example:
abstract class My { public void mymethod() { System.out.print("Abstract"); } } class Poly { public static void main(String a[]) { My m = new My() {}; m.mymethod(); } }
Contrary to traditional notions, it is possible to instantiate an abstract class in this scenario. However, there is a subtle difference: instead of instantiating the abstract class itself, we are creating an anonymous subclass of it.
Understanding Anonymous Subclasses
An anonymous subclass is an unnamed inner class that extends or implements a specified superclass or interface. In the above code:
Validation Through Compilation
To verify this behavior, consider compiling the code. In the compiled output, we will notice:
The presence of Poly$1.class confirms the instantiation of an anonymous subclass, not the abstract class itself.
Java Language Specification Support
The Java Language Specification (JLS) explicitly mentions anonymous subclasses in Section 15.9.1: "The class being instantiated is the anonymous subclass."
Conclusion
While abstract classes cannot be directly instantiated, they can be extended by anonymous subclasses, allowing for the creation of instances with customized methods and fields. This nuance is a valuable tool for understanding and utilizing Java's object-oriented concepts.
The above is the detailed content of Can We Instantiate an Abstract Class in Java?. For more information, please follow other related articles on the PHP Chinese website!