Introduction
In this session, we will learn about use of inheritance and advantages of inheritance, inheritance syntax, and inheritance concepts.
First, let's look at the example explaining why we need inheritance.
- Public class FulltimeEmployee
- {
- public String First Name;
- public String Last Name;
- public String Email;
- public Float yearly Salary;
- Pubic void Printfullname ()
- {
- }
- }
- Public class PartTimeEmployee
- {
- public String First Name;
- public String Last name;
- public String Email;
- public String Hourly Rate;
- Public void Printfullname ()
- {
- }
- }
The code between these two classes is duplicated because certain things are common in FulltimeEmployee and PartTimeEmployee class, like Firstname, Lastname, Email. A small difference between these two is yearly Salary and Hourly Rate. Now, let's explain inheritance using these two classes in one common class Employee.
- Public class Employee
- {
- public String First Name; /* Common Code moved into Base Employee class
- public String Last name;
- public String Email;
- Public void PrintFullName ()
- {
- }
- }
- Public class FulltimeEmployee () /* Fulltime and Part-time Employee Specific Code in Respective
- { Derived classes */
- Float Yearly salary;
- }
- Public class ParttimeEmpoyee ()
- {
- Float Hourlysalaty;
- }
What is the advantage of doing this -
- Code reused
- A lot of coding time is saved.
Let's now explain the code. I have created "Employee" base class where all common attributes are defined.
- public class FulltimeEmployee:Empolyee
- {
- public float YearlySalary;
- }
- public class ParttimeEmployee:Empolyee
- {
- public float HourlySalary;
- }
- using System;
- public class Empolyee
- {
- public string Firstname;
- public string Lastname;
- public string Email;
- public void printfulName()
- {
- Console.WriteLine(Firstname + " " + Lastname);
- Console.ReadLine();
- }
- }
- public class FulltimeEmployee:Empolyee
- {
- public float YearlySalary;
- }
- public class ParttimeEmployee:Empolyee
- {
- public float HourlySalary;
- }
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- FulltimeEmployee FTE = new FulltimeEmployee();
- FTE.Firstname = "Thenn";
- FTE.Lastname = "Arasu";
- FTE.Email = "[email protected]";
- FTE.YearlySalary = 5000; //Full Time Employee Specific Fields
- FTE.printfulName(); //called print the Name to printfulName base class Method
- ParttimeEmployee PTE = new ParttimeEmployee();
- PTE.Firstname = "Karthi";
- PTE.Lastname = "Keyan";
- PTE.Email = "[email protected]";
- PTE.HourlySalary = 5000;
- PTE.printfulName(); // called print the Name to printfulName base class Method
- }
- }
- }


Muhammad Asif ShahzadPosted Feb 5, 2018, 12:12 AM
(Y) its really helpful for the bigger, Thanks keep it up
Anu VPosted Mar 20, 2017, 5:14 AM
Nice article.. Thanks for sharing..
SubashPosted Mar 18, 2017, 1:40 AM
Good start keep sharing