Junior — Middle
Description of the abstract class concept in Java and its main purpose.
sobes.tech AI
Answer from AI
An abstract class in Java is a class that cannot be instantiated directly and is intended to serve as a base structure from which other classes inherit. It can contain both implemented methods and abstract methods (without implementation), which must be overridden in subclasses.
The main purpose of an abstract class is to define a common interface and behavior for a group of related classes, while allowing subclasses to implement specific logic.
Example:
abstract class Animal {
abstract void makeSound(); // abstract method
void sleep() {
System.out.println("Sleeps");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
// Cannot create an object of Animal directly:
// Animal a = new Animal(); // Error
Dog dog = new Dog();
dog.makeSound(); // Outputs: Bark
dog.sleep(); // Outputs: Sleeps