Wednesday, March 31, 2021

What is Inheritance in C#?

Inheritance is a relationship between a base and its derived class. 

  • Base class
    • Also called the Parent class
    • This can be reusable by being inherited to the child classes
  • Derived class
    • The child class inheriting its parent
Advantages of using Inheritance
  • Provides resubility of existing implementation
  • Polymorphism, will see more on dedicated post that helps the same
Example,

class Vehicle
{
    public string make;
    
    public void StartEngine
    {
        //Different ways, its implementation
    }

}

class Car : Vehicle         //class Car Inherits from Parent class Vehicle
{
    public string model;
}

Now class Car has its own property model and it has also inherited the properties from Vehicle class as used Inheritance.

So creating intance of the class will allow you to use both as given below,

Car myCar = new Car();
myCar.make = "Mercedes";          //Inherited property
myCar.model = "C Class";            //Own property
myCar.StartEngine();                     //Inherited method


Sealed keyword in C# restrict the Inheritance of the class. 
Example,

sealed class Vehicle
{
    //implementation
}

class Car : Vehicle    //This is not allowed due to sealed keyword
{
    //
implementation

Will see more on scenario base queries on Sealed keyword dedicated topic. 

Abstract Classes
  • It is a half defined class, becuase it can have an abstract implementation and hence no instance can be created of abstract classes
  • This is helpful to create a base class to provide primary implementation to be followed for their child classes
  • All the abstract methods declaration requires its child classes do have an implementation of the same
  • Virtual Methods helps child classes to Override the same and change their own logic 
Interface
  • It's a contract 
  • classes that inherite the interface must have to implement all the methods from that Interface
  • Instance creation is not allowed
  • Helps to standardize coding practice across multiple classes
Hide base class member
  • if parent and child classes share the same name for their methods, the new modifier at method definition helps to hide the base class implementation

No comments:

Post a Comment

C# Interview Prep: 100 Common Questions for 0-3 Years Experience

Common C# Interview Questions  Basics of C# Language: What is C#? C# (pronounced C sharp) is a modern, object-oriented programming language...