Junior — Middle
What are the main functions and applications of abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes in object-oriented programming are classes that are not intended to be instantiated directly, but serve as base templates for other classes.
Main functions of abstract classes:
- Defining a common interface and basic behavior for a group of related classes.
- The ability to declare abstract methods (without implementation) that must be implemented by subclasses.
- Allowing partial implementation of functionality that is inherited by child classes.
Applicability:
- When you need to set a common contract for different implementations.
- When part of the logic is common, and part needs to be implemented in subclasses.
Example in Java:
abstract class Animal {
abstract void makeSound(); // abstract method
void breathe() {
System.out.println("Breathing");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark-bark");
}
}
Here, Animal cannot be created directly, but you can create a Dog, which implements the makeSound method.