Junior — Middle
Explain the concept of inheritance in object-oriented programming
sobes.tech AI
Answer from AI
Inheritance in object-oriented programming is a mechanism that allows creating a new class based on an existing one, where the new class (child) inherits all properties and methods of the base class (parent). This promotes code reuse and simplifies the extension of functionality.
For example, there is a base class Animal with a method makeSound(). The class Dog can inherit from Animal and override the method to produce a specific sound:
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
Thus, inheritance allows creating class hierarchies where subclasses specialize or extend the behavior of parent classes.