Inheritance
Inheritance means creating a new class based on an existing class. The new class inherits attributes and methods from the existing class.
Example Explanation
Imagine you have a general class called Animal. You can create a specific class called Dog that inherits everything from Animal and adds its own features.
code
Explanation of the Example
-
Animal class (Parent class):
- Has an attribute 'name'.
- Has a method 'eat'.
-
Dog class (Child class):
- Inherits everything from 'Animal'.
- Adds its own method 'bark()'.
-
my_dog Object:
- Can use the 'eat()' method from 'Animal'.
- Can use the 'bark()' method from 'Dog'.
Polymorphism
Polymorphism means "many shapes". It allows methods to do different things based on the object it is acting upon, even if they share the same name.
Example Explanation
Let's continue with the 'Animal' and 'Dog' classes, and add another class called 'Cat'.
Code
Explanation of the Example
-
Animal Class:
- Has a method 'make_sound()' that prints a generic message.
-
Dog Class:
- Inherits from 'Animal'.
- Overrides 'make_sound()' to print a dog-specific message.
-
Cat Class:
- Inherits from 'Animal'.
- Overrides 'make_sound()' to print a cat-specific message.
-
my_dog and my_cat Objects:
- Both use the make_sound() method, but each prints a different message based on their class.
Summary
- Inheritance: Allows a class to inherit attributes and methods from another class.
- Polymorphism: Allows methods to do different things based on the object they are called on, even if they share the same name.
In next article we will Explore Abstraction & Encapsulation and please give me your feedback
Top comments (0)