Single Level Inheitance: Inheriting Fields
using System; namespace InheitanceCsharp { public class Employee { public float salary = 40000; } public class Programmer : Employee { public float bonus = 10000; } class TestInheritance { public static void Main(string[] args) { Programmer p1=new Programmer(); Console.WriteLine("Salary: "+p1.salary); Console.WriteLine("Bonus: "+p1.bonus); Console.ReadKey(); } } }
Single Level Inheritance: Inheriting Methods
using System; namespace InheritMethod { public class Animal { public void eat() { Console.WriteLine("Eating..."); } } public class Dog : Animal { public void bark() { Console.WriteLine("Barking..."); } } class TestInheritance { public static void Main(string[] args) { Dog d1=new Dog(); d1.bark(); d1.eat(); Console.ReadKey(); } } }
Multilevel Inheritance:
//multiple inheritance is not supported in c# through class //so it supports naturally multi level inheritance //but we can use multiple inheritance using interface using System; namespace MultiLevelInheitance { public class Animal { public void eat() { Console.WriteLine("Eating.."); } } public class Dog : Animal { public void bark() { Console.WriteLine("Barking....."); } } public class BabyDog : Dog { public void weep() { Console.WriteLine("Weeping..."); } } public class BabyBabyDog : BabyDog { public void Cry() { Console.WriteLine("Crying..."); } } class TestInhertance { static void Main(string[] args) { BabyBabyDog bb=new BabyBabyDog(); bb.eat(); bb.bark(); bb.weep(); bb.Cry(); Console.ReadLine(); } } }
Multiple Inheritance Through Interface:
//interface is just like class here using System; namespace MultipleInheritanceInterface { interface calc1 { int add(int a, int b); } interface calc2 { int sub(int x, int y); } interface calc3 { int mul(int r, int s); } interface calc4 { int div(int c,int d); } class calculation : calc1, calc2, calc3, calc4 { public int result1; public int add(int a, int b) { return result1 = a + b; } public int result2; public int sub(int x, int y) { return result2 = x - y; } public int result3; public int mul(int r,int s) { return result3 = r * s; } public int result4; public int div(int c, int d) { return result4 = c / d; } } class Program { static void Main(string[] args) { calculation c=new calculation(); c.add(8, 2); c.sub(20, 10); c.mul(5,2); c.div(20, 10); Console.WriteLine("Multiple ineritance concept using interface:\n"); Console.WriteLine("Addition:"+c.result1); Console.WriteLine("Substraction:"+c.result2); Console.WriteLine("Multiplication:"+c.result3); Console.WriteLine("Division:"+c.result4); Console.ReadKey(); } } }