Among the prominent overriding members, Inheritance is the most valuable member to create a new class that re-utilizes, expands, and updates the performance that is defined in some other class.
Base class and Derived class
Throughout inheritance, mainly two types of classes are used such as Base class and derived class. Generally, the class whose members get inherited is known as the base class, and the class, which inherits those members, is known as the derived class. On the other hand, whole classes in C# completely inherit from the Object class, which supports .NET class hierarchy and offers low-level services to whole classes.
But, C# never supports multiple inheritances and hence, only one base class will be specified for one derived class.
Codes to inherit from a base class:
Usually, all classes can be inherited as per the OOPS concept of C#. However, you have the option to specify whether a class should be used as a base class, or not. It all depends upon you to decide about creating a base class.
Find the following Codes to specify that a class cannot be used as a base class:
1 public sealed class A { }
Following codes are used to denote that a class can be used as a base class only and also, cannot be instantiated:
1 public abstract class B { }
Overriding Members
Generally, a derived class inherits all required members from the specific base class. If you wish to alter the actions of the inherited member, you have to override it definitely with some overriding members. Also, you can define a new execution of the method, event, or property in the present derived class.
The following C# modifiers are used in overriding the properties and methods.
C# Modifier and Definition
Virtual - It allows a specific class member to be overridden within a derived class.
Override - This modifier overrides a virtual or override able member that is defined within the base class.
Abstract - Describes that a class member can be overridden within the derived class by inheriting the class member from the base class.
Sealed - Specifies about non-use of class as a base class
New Modifier - Hides a particular member that is inherited from a base class as per requirement.
What are Interfaces?
Interfaces are similar to classes, which define a set of methods, properties, and events. But unlike classes, interfaces disallow implementation directly. They’re implemented through classes and defined as detach entities from classes. An interface stands for a contract in that a class, which implements an interface, needs to implement each aspect of the same interface accurately as it is defined.
Codes to define an interface:
1 interface ITCInterface
2 {
3 void DoSomething();
4 }
Codes to implement an interface within a class:
1 class SampleClass : ITCInterface
2 {
3 void ITCInterface.DoSomething()
4 {
5 // implementation method.
6 }
7 }
Hope the readers have thorough knowledge about the use of code for Inheritance, Overriding members and interfaces.
Top comments (0)