Inheritance: The most important reason to use OOP is to make reusability of Code and eliminate the redundant code. That can be done by one of the OOP concept i.e - -> INHERITANCE. Inheritance supports reusability by defining a class and then use that class again and again.
Inheritance supports a class hierarchy where Base class and Derived class exist, Suppose - -> Animals is the [Base Class] and Dog is the [Derived Class].Derived Class inherits the base class. Also Derived Class can inherits all the member of Base Class.
Let’s Begin our Program!.
Step 1: Open your Visual Studio. By pressing Ctrl +Shift + N you will get your “New Project” Window.
Figure 1: Create Console Application
Step 2: After pressing OK you will get into your Coding Part where you will see three files in Solution Explorer [Properties, References, Program.cs], in which Program.cs file is your main file where you embed all your Inheritance program code.
Figure 2: Solution Explorer
This is your Code for Inheritance Program:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Inheritance_demo21
- {
- public class Baseclass {
- public int datamember;
- public void baseclassmethod()
- {
- Console.WriteLine("This is baseclass method");
- Console.WriteLine("-----------------------------------");
- }
- }
- public class DerivedClass : Baseclass
- {
- public void derivedclassmethod()
- {
- Console.WriteLine("This is our derivedclassmethod");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
-
- Baseclass bc = new Baseclass();
- bc.datamember=1;
- bc.baseclassmethod();
-
-
-
- DerivedClass dc = new DerivedClass();
- dc.datamember = 2;
- dc.derivedclassmethod();
- dc.baseclassmethod();
- Console.ReadKey();
-
- }
- }
- }
Output
Press F5 to get your output, you will get something like this :
Figure 3: Output
Hope you like it! Have a nice day. Thank you for Reading!