Junior — Middle
Can you explain the essence of inheritance in object-oriented programming?
sobes.tech AI
Answer from AI
Inheritance is one of the key principles of object-oriented programming, which allows creating a new class based on an existing one. The new class (child) inherits all properties and methods of the base class (parent), and can also add its own or override inherited ones.
This allows:
- Reusing code without duplication.
- Creating class hierarchies that reflect 'is-a' relationships.
- Ensuring polymorphism, where objects of different classes can be used through a common interface.
Example in Python:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Woof")
dog = Dog()
dog.speak() # Outputs: Woof
Here, the Dog class inherits the speak method from Animal but overrides it to provide specific behavior.