Title
Understanding Inheritance in C# – Part 3
Introduction
In my last two article we’ve discussed on what is inheritance and have seen two types of inheritance Single and Hierarchical inheritance.
In this post we will see Multilevel Inheritance.
When one class is derived from another derived class then this type of inheritance is called multilevel inheritance.
Class File
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class person { private string name = ""; private long phno; public void read() { Console.Write("Enter name: "); name = Console.ReadLine(); Console.WriteLine(); Console.Write("Enter phone number: "); phno = Convert.ToInt64(Console.ReadLine()); Console.WriteLine(); } public void show() { Console.WriteLine("Name is: " + name); Console.WriteLine("Phone number is: " + phno); } } class student : person { private long rollno; private string course; new public void read() { base.read(); Console.Write("Enter roll no: "); rollno = Convert.ToInt64(Console.ReadLine()); Console.WriteLine(); Console.Write("Enter course name: "); course = Console.ReadLine(); Console.WriteLine(); } new public void show() { base.show(); Console.WriteLine("Roll number is: " + rollno); Console.WriteLine("Course name is: " + course); } } class exam : student { private int[] m = new int[4]; private double per; int tot_marks = 0; new public void read() { base.read(); Console.Write("Enter Marks: "); for (int i = 0; i < 4; i++) { m[i] = Convert.ToInt32(Console.ReadLine()); } } public void cal() { for (int i = 0; i < 4; i++) { tot_marks = tot_marks + m[i]; } per = Convert.ToDouble((tot_marks) / 4); } new public void show() { base.show(); Console.WriteLine("Marks are: "); for (int i = 0; i < 4; i++) { Console.WriteLine(m[i]); } Console.WriteLine(); Console.WriteLine("Total Marks: " + tot_marks); Console.WriteLine("Percentage is: " + per); } } }
Main Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { exam e1 = new exam(); e1.read(); e1.cal(); e1.show(); } } }
Output
Note
C# does not support multiple inheritances of classes. To overcome this problem we can use interfaces, I’ll be discussing about inheritance in upcoming articles.
Inheritance series ends here, hope you have enjoyed and have learn the basics of inheritance.
Happy Coding.