Software & Finance





C# - Inheritance





Inheritance means classes can be derived from another class called base class. Derived classes will have all the features of the base class and it will have access to base class protected and public members. Derived classes will not have access to private members of the base class.

 

We know C++, C# and Java supportes inheritance. But there are differences in the inheritance implementation between C++, C# and Java Inheritance. In C++, you need to use the virutal keyword in both base and derived classes. In C#, you need to use virual keyword in base case and override keyword in derived classes.

 

In Java you do not need to use any keyword like virtual or override since by default all non static functions are considered as virual. You have to make it either private or use final keyword to remove the default virtual feature in each function in the Java classes.

 

When writing derived classes C++ and C# uses ":" between derived class and base class. Java uses extends keyword instead of :

 

Useful links:

Inheritance in C++

Inheritance in C#

Inheritance in Java


 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Inheritance

{

 

    class Shape

    {

 

        public Shape()

        {

            System.Console.WriteLine("Shape");

        }

 

        public virtual void draw()

        {

            System.Console.WriteLine("Drawing Shape");

        }

    }

 

 

    class Circle : Shape

    {

        int r;

 

        public Circle()

        {

            System.Console.WriteLine("Circle");

        }

 

        public override void draw()

        {

            System.Console.WriteLine("Drawing Circle");

        }

    }

 

 

 

    class Triangle : Shape

    {

        public int a,b,c;

 

        public Triangle()

        {

            System.Console.WriteLine("Triangle");

        }

 

        public override void draw()

        {

            System.Console.WriteLine("Drawing Triangle");

        }

    }

 

    class InheritanceSample

    {

        static void Main()

        {

            Shape s1 = new Shape();

            Shape s2 = new Circle();

            Shape s3 = new Triangle();

 

            System.Console.WriteLine("\n\nNow Drawing Objects\n");

 

            s1.draw();

            s2.draw();

            s3.draw();

 

            System.Console.WriteLine("\n");

        }

    }

}

Output


Shape

Shape

Circle

Shape

Triangle

 

 

Now Drawing Objects

 

Drawing Shape

Drawing Circle

Drawing Triangle

 

Press any key to continue . . .