DPnew
DPnew
Inheritance in
Object-Oriented
Programming
Inheritance is a fundamental concept in object-oriented
programming (OOP). It allows you to create new classes that
inherit properties and methods from existing classes. This
promotes code reusability and creates a hierarchical relationship
between classes.
Inheritance Types: Single,
Multilevel, and
Hierarchical
1 Single Inheritance 2 Multilevel Inheritance
A derived class inherits from A derived class inherits from
only one base class. This is another derived class,
the simplest and most creating a chain of
common type of inheritance. inheritance.
2 Parent
The parent class inherits from the grandparent class. It inherits all
the properties and methods of the grandparent and can add its
own specific traits. For example, a "Parent" class might have a new
method called "Work()."
3 Child
The child class inherits from the parent class. It inherits all the
properties and methods of the parent and can add even more
specialized features. For example, a "Child" class might have a
new method called "Play()."
Technical Example: Inheritance in C#
Base Class Derived Class Inheritance
The base class, "Animal," defines The derived class, “Bird," inherits Inheritance allows you to create a
common properties like "Name" from "Animal." It can access and “Bird" object that can use "Name"
and "Age." It also contains reuse all the properties and and "Age" from the "Animal" class
methods like "Move()." methods of "Animal" and can also and also “Fly()." It promotes code
add its own specific behaviors like reusability and reduces
“Fly()." redundancy.
Code Snippet: Implementing
Single Inheritance in C#
class Animal
{ public:
int age;
string name;
Animal(int a) : age(a)
void eat()
{ std::cout << "This animal is eating." << std::endl; }
virtual void move()
{ std::cout << "This animal is moving." << std::endl;
};