Middle
Is it possible to create an object of an abstract class in Java?
sobes.tech AI
Answer from AI
In Java, you cannot create an object of an abstract class directly, because an abstract class is intended to serve as a base for other classes and may contain abstract methods without implementation. However, you can create an object of an anonymous subclass of the abstract class, implementing all abstract methods on the spot.
Example:
abstract class Animal {
abstract void sound();
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal() {
void sound() {
System.out.println("Meow");
}
};
a.sound(); // Will output "Meow"
}
}
Thus, the object is not created directly from an abstract class, but from an anonymous class that inherits from it and implements all abstract methods.