Home >Java >javaTutorial >Can Abstract Classes Be Instantiated in Java?

Can Abstract Classes Be Instantiated in Java?

DDD
DDDOriginal
2024-12-24 15:57:18292browse

Can Abstract Classes Be Instantiated in Java?

Can We Instantiate an Abstract Class?

During an interview, you were asked if it's possible to instantiate an abstract class. Tradi tionally, you would respond "no." However, the interviewer surprised you by saying it's possible.

To demonstrate this, 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();
    }
}

Despite the abstract modifier on my, you can create an instance of it using an anonymous subclass. You're essentially creating a subclass on the fly and assigning its reference to the abstract class reference m.

According to the Java Language Specification (JLS):

"If the class instance creation expression ends in a class body, then
the class being instantiated is an anonymous class."

So, in this case, the class being instantiated is not my, but an anonymous subclass.

This behavior can be confirmed by compiling the code and checking the generated class files. You will notice a new class file named Poly$1.class, which corresponds to the anonymous subclass created at runtime.

Therefore, while you cannot directly instantiate an abstract class, you can effectively achieve the same result by creating an anonymous subclass.

The above is the detailed content of Can Abstract Classes Be Instantiated 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