Example about inheritance in C#: assume that we have class Animal contains information about Name and number of its foot. Now we create some class to be inheritance from class Animal
using System; using System.Collections.Generic; using System.Text; namespace __OOP_Inheritance { class Program { static void Main(string[] args) { Dog objDog = new Dog(4); objDog.displayProperties(); Chicken objChicken = new Chicken(2); objChicken.displayProperties(); Console.Read(); } } class Animal { protected int ifoots; protected string sName; protected void setFoot(int ival) { ifoots = ival; } protected void setName(string sVal) { sName = sVal; } public void displayProperties() { Console.WriteLine(sName + " have " + ifoots.ToString()+ " foots"); } } class Dog : Animal { public Dog(int ival) { setName("Dog"); ifoots = ival; } } class Chicken : Animal { public Chicken(int ival) { setName("Chicken"); setFoot(ival); } } }
If you want to override function public void displayProperties(), You should set it virtual. Like This:
using System; using System.Collections.Generic; using System.Text; namespace __OOP_Inheritance { class Program { static void Main(string[] args) { Dog objDog = new Dog(4); objDog.displayProperties(); Chicken objChicken = new Chicken(2); objChicken.displayProperties(); Tiger objTiger = new Tiger(4); objTiger.displayProperties(); Console.Read(); } } class Animal { protected int ifoots; protected string sName; protected void setFoot(int ival) { ifoots = ival; } protected void setName(string sVal) { sName = sVal; } public virtual void displayProperties() // Changed here { Console.WriteLine(sName + " has " + ifoots.ToString()+ " foots"); } } class Dog : Animal { public Dog(int ival) { setName("Dog"); ifoots = ival; } } class Chicken : Animal { public Chicken(int ival) { setName("Chicken"); setFoot(ival); } public void displayProperties() { base.displayProperties(); Console.WriteLine(sName + " have " + ifoots.ToString() + " foots (from Chicken class)"); } } class Tiger : Animal { public Tiger(int ival) { setFoot(ival); } public override void displayProperties() // override here { Console.WriteLine("Tiger has " + ifoots.ToString()+ " foots"); } } }
I also have foots. Only sheeple have feet
ReplyDeleteWake up
ReplyDelete