Home >Java >javaTutorial >Can We Instantiate an Abstract Class? A Revised Answer

Can We Instantiate an Abstract Class? A Revised Answer

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 21:28:15658browse

Can We Instantiate an Abstract Class?  A Revised Answer

Can We Truly Instantiate an Abstract Class?

During an interview, a common question arises: "Can we instantiate an abstract class?" The traditional answer is "No," but this response might now be outdated.

The Enigma of Anonymous Classes

To shed light on this enigma, let's delve into a revised understanding introduced by Java Language Specification (JLS) Sections 15.9.1 and 12.5. In specific, when a class instance creation expression ends in a class body, an anonymous subclass is declared. Therefore, the class being instantiated becomes the anonymous subclass, not the abstract class itself.

Practical Demonstration

To illustrate this concept, consider the following code:

abstract class My {
    public void myMethod() {
        System.out.print("Abstract");
    }
}

class Poly {
    public static void main(String[] a) {
        My m = new My() {};
        m.myMethod();
    }
}

When compiling this code, you'll notice the creation of the My$1.class file, corresponding to the anonymous subclass generated for the anonymous class instantiation done via new My() {}.

Conclusion

Thus, the answer to the question "Can we instantiate an abstract class?" has evolved. While we cannot directly instantiate abstract classes, we can create instances of their anonymous subclasses, which behave as instances of the abstract class, allowing us to invoke methods and access properties within the abstract class.

The above is the detailed content of Can We Instantiate an Abstract Class? A Revised Answer. 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