Junior — Middle
Is it possible to instantiate a class that contains only abstract methods?
sobes.tech AI
Answer from AI
In Java, you cannot instantiate (create an instance of) a class if it contains only abstract methods and is declared as an abstract class. An abstract class is a class that may contain abstract methods (without implementation), and it cannot be instantiated directly. To use such a class, you need to create a subclass that implements all abstract methods, and then this subclass can be instantiated.
Example:
abstract class Animal {
abstract void makeSound();
}
// Not allowed: Animal a = new Animal(); // Compilation error
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
Dog dog = new Dog(); // Allowed