Search This Blog

Tuesday, 24 May 2016

INHERITANCE

Definition 1: Inheritance describes the ability to create new classes based on an existing class.

Definition 2: Inheritance is the process by which one object acquires the properties of another object. A type derives from a base type, taking all the base type members fields and functions.
Inheritance is most useful when you need to add functionality to an existing type.

Definition 3: The process of sub-classing a class to extend its functionality is called Inheritance.
It provides the idea of reusability.

Examples:

1. Human heredity- a child acquiring the characteristics of its parents or grandparents.
2. A Scientific calculator is a extended form a calculator. (here calculator is parent and scientific calculator is Child object.

Classification of Inheritance

1. Single
2. Multiple (Not supported)
3. Multi-level
4. Hierarchical
5. Hybrid

1. Single Inheritance

When a single derived class is created from single base class then the inheritance is called as single inheritance.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class BaseClass
    {
        //method to print given 2 numbers
        //When declared protected, can be accessed only from inside the derived class
        //cannot access with the instance of derived class
        protected void print(int x, int y)
        {
            Console.WriteLine("First Number:" + x);
            Console.WriteLine("Second Number:" + y);
        }
    }
    class Derivedclass : BaseClass
    {
        public void print3numbers(int x, int y, int z)
        {
            print(x, y);//We can directly call baseclass members
            Console.WriteLine("Third Number:" + z);
        }
    }
    class MainClass
    {
        static void main(string[] args)
        {
            //Create instance for derived class, so that base class members can also be accessed
            //This is possible because derivedclass in inheriting base class

            Derivedclass instance = new Derivedclass();

            instance.print3numbers(30, 40, 50);//Derived class internally calls base class method.           
            Console.Read();
        }
    }
}

Output:

First Number: 30
Second Number: 40
Third Number: 50




No comments:

Post a Comment