Friday 27 May 2016

Inheritance

Inheritance In simple inheritance means you can access data member of base class from the derived class. Base class is the class which has data member. And derived class is the class which is used to inherit data from the base class. Inheritance is second pillar of OOP (Object Oriented Programming) concept. Take one example of father and son relationship. Son can inherits habits from his father. How to define inheritance? Using ‘:’ operator you can inherit class to derived class. class myBase { //base class body } class myDerived: myBase { //derived class body } Example: using System; class Program { static void Main() { Car cr = new Car(1, "Ascent"); } } class Vehicle { //private fields private int _id; private string _name; //public properties public int Id { get { return _id; } set { _id = value; } } public string Name { get { return _name; } set { _name = value; } } public Vehicle(int id, string name) { Console.WriteLine("I am vehicle."); this._id = id; this._name = name; } } class Car: Vehicle { public Car(int id,string name):base(id,name) { Console.WriteLine("I am Car."); Console.WriteLine("--------------------"); Console.WriteLine("ID\tName"); Console.WriteLine("--------------------"); Console.WriteLine("{0}\t{1}",base.Id,base.Name); Console.WriteLine("--------------------"); } } Output: I am Vehicle. I am Car. ------------------------------------------ ID Name ------------------------------------------ 1 Ascent ------------------------------------------ Press any key to continue… In above example we have created Vehicle and Car class Car inherits Vehicle property and parameter constructor of vehicle to assign id and name value to private fields of vehicle class. So here Vehicle is a base class where Car is derived class which inherits public fields, properties, constructor and methods.

No comments:

Post a Comment