advertisement
Inheritance in C#
Inheritance
A programmer does not always have to create a class in a C# application from scratch. At times, the programmer can create a new class by extending the features of an existing class. The process of creating a new class by extending some features of an existing class is known as inheritance.
//Example 1: Basic inheritance
//Base Class
class animal
{
public string name { get; set; }
public void eat()
{
Console.WriteLine($"{name} is eating");
}
}
// Derived Class
class dog : animal
{
public void bark()
{
Console.WriteLine($"{name} is Barking");
}
}
class program
{
static void Main()
{
dog dogobj = new dog();
dogobj.name = "Buddy";
dogobj.eat(); //inherited method
dogobj.bark(); // method specific to dog class
Console.ReadKey();
}
}
1. Definition of Inheritance
The similarity in physical features of a child to that of its parents is due to the child having inherited these features from its parents. Similarly, in C#, inheritance allows you to create a class by deriving the common attributes and methods of an existing class.
The class from which the new class is created is known as the base class and the created class is known as the derived class.
For example, consider a class called vehicle that consists of a variable called color and a method called Speed (). These data members of the Vehicle class can be inherited by the TwoWheelerVehicle and FourWheelerVehicle classes.
2. Purpose
The purpose of inheritance is to reuse common methods and attributes among classes without recreating them. The reusability of a code enables you to use the same code in different applications with little or no changes. Consider a class named Animal which defines attributes and behavior for animals. If a new class named Cat has to be created, it can be done based on Animal because a cat is also an animal. Thus, you can reuse the code from the previously defined class.
Apart from reusability, inheritance is widely used for:
- Generalization: inheritance allows you to implement generalization by creating base classes. For example, consider the class vehicle, which is the base class for its derived classes Truck and Bike. The class vehicle Consists of general attributes and methods that are implemented more specifically in the respective derived classes.
- Specialization: Inheritance allows you to implement specialization by creating derived classes. For example, the derived classes such as Bike, Bicycle, Bus, and Truck are specialized by implementing only specific methods from its generalized base class vehicle.
- Extension: Inheritance allows you to extend the functionalities of a derived class by creating more methods and attributes that are not present in the base class. It allows you to provide additional features to the existing derived class without modifying the existing code.
3. Multi-level Hierarchy
Inheritance allows the programmer to build hierarchies that can contain multiple levels of inheritance For example, consider three classes Mammal, Animal, and Dog. The class Mammal is inherited from the base class Animal, which inherits all the attributes of the Animal class. The class Dog is inherited from the class Mammal and inherits all the attributes of both the Animal and Mammal classes.
4. Implementing Inheritance
The syntax to derive a class from another class is quite simple in C#. You just have to insert a colon after the name of the derived class followed by the name of the base class. The derived class can now inherit all non-private methods and attributes of the base class.
The following syntax is used to inherit a class in C#:
Syntax
<DerivedclassName> : <BaseClassName>
where,
DerivedclassName: This is the name of the newly created child class.
BaseClassName: ls the name of the parent class from which the current class is inherited.
following syntax is used to invoke a method of the base class:
Syntax
<objectName>, <MethodName >;
where,
ObjectName: This is the object of the base class.
MethodName: This is the name of the method of the base class.
5. protected Access Modifier
The protected access modifier protects the data members that are declared using this modifier. The protected access modifier is specified using the protected keyword. Variables or methods that are declared as protected are accessed only by the class in which they are declared or by a class that is derived from this class.
6. Base keyword
The base keyword allows you to access the variables and methods of the base class from the derived class. When you inherit a class, the methods and variables defined in the base class can be re-declared in the derived class. Now, when you invoke methods or access variables, the derived class data members are invoked and not data members of the base class. In such situations, you can access the base class members using the base keyword.
You cannot use the base keyword for invoking the static methods of the base class.
7. new Keyword
The new keyword can either be used as an operator or as a modifier in C#. The new operator is used to instantiate a class by creating its object. This instantiation finally invokes the constructor of the class. As a modifier, the new keyword is used to hide the methods or variables of the base class that are inherited in the derived class. This allows you to redefine the inherited methods or variables in the derived class. Since redefining the base class members in the derived class results in base class members being hidden, the only way you can access these is by using the base keyword.
8. Constructor Inheritance
In C#, you cannot inherit constructors similar to how you inherit methods. However, you can invoke the base class constructor by either instantiating the derived class or the base class. The instance of the derived class will always first invoke the constructor of the base class followed by the constructor of the derived class. In addition, you can explicitly invoke the base class constructor by using the base keyword in the derived class constructor declaration. The base keyword allows you to pass parameters to the constructor.
// Example 2: inheritance with constructor
//base class
class shape
{
public double width { get; set; }
public double height { get; set; }
public shape(double width,double height)
{
this.width = width;
this.height = height;
}
public double area()
{
return width * height;
}
}
// Derived class
class rectangle : shape
{
public rectangle(double width,double height): base(width, height)
{
}
}
class program
{
static void Main()
{
rectangle myrec = new rectangle(10,3);
Console.WriteLine($"rectangle area : { myrec.area()}");
Console.ReadKey();
}
}
9. Invoking the parameterized base class constructor
The derived class constructor can explicitly invoke the base class constructor by using the base keyword. if a base class constructor has a parameter, the base keyword is followed by the value of the type specified in the constructor declaration. of there are no parameters, the base keyword is followed by a pair of parentheses.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0