Middle
Kas Java-s on võimalik luua abstraktse klassi objekti?
sobes.tech AI
Vastus AI-lt
In Java, it is not possible to directly create an object of an abstract class, because an abstract class is intended to serve as a base for other classes and can contain abstract methods without implementation. However, it is possible to 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 print "Meow"
}
}
Thus, the object is not created directly from the abstract class, but from an anonymous class that inherits from it and implements all abstract methods.