Home >Java >javaTutorial >Can We Instantiate an Abstract Class in Java?

Can We Instantiate an Abstract Class in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 10:57:16815browse

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:

  • new My() creates an instance of the anonymous subclass that extends My.
  • The class body {} allows us to define methods and fields specifically for this instance.
  • m is a reference to the instance of the anonymous subclass, accessing its overridden mymethod().

Validation Through Compilation

To verify this behavior, consider compiling the code. In the compiled output, we will notice:

  • My.class: The bytecode for the abstract class.
  • Poly.class: The bytecode for the enclosing class.
  • Poly$1.class: The bytecode for the anonymous subclass.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn