What is Inheritance?
What is Inheritance in computer programming?
Inheritance is a programming concept that allows a new class to be based on an existing class, inheriting its properties and methods.
Here’s an example of inheritance for python.
# Define a base class class Animal: def make_sound(self): print("This animal makes a sound.") # Define a subclass that inherits from Animal class Dog(Animal): def make_sound(self): print("Woof!") # Create an instance of the Dog class and call its methods my_dog = Dog() my_dog.make_sound() # Output: "Woof!"
Inheritance is a major concept in Object Oriented Programming. it refers to a process in which a new class is derived by the properties of the existing classes (parent/base classes). This newly created class is known as the derived class or inherited class.
Let me explain this concept with the help of an example using Java:
Let us assume a class called “Person”
class Person { public int eyes = 2; public int nose = 1; public int mouth = 1; }
Now, the Person class can act as the base class for our new derived class Cricketer.
class Cricketer extends Person { String batsman = "left handed"; String bowler = "off spin"; boolean wicketKeeper = false; }
In object-oriented programming, inheritance is a mechanism that allows a new class to be based on an existing class, inheriting some or all of its properties and behaviors. The existing class is called the base class or parent class, while the new class is called the derived class or child class.
When a class inherits from a parent class, it gains access to all the public and protected properties and methods of the parent class. This allows the derived class to reuse the code and behavior of the parent class, while also adding new functionality or modifying existing behavior as needed.
- 14 Forums
- 1,836 Topics
- 5,052 Posts
- 0 Online
- 1,078 Members