Tuesday 21 July 2009

OOP Basics: Inheritance

This little article is a basic introduction of using inheritance in C#. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming. Let's take a look at the program below:

using System;

namespace InheritanceSample
{
public class Parent
{

string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}

public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}

public void print()
{
Console.WriteLine("I'm a Parent Class.");
}

}

public class Child : Parent
{

public Child(): base("From Parent")
{
Console.WriteLine("Child Constructor.");
}

public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}

public static void Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
}

Output:


Base classes are automatically instantiated before derived classes. Notice the output from above: The Parent constructor executed before the Child constructor. When a base class declares a method as virtual, a derived class can override the method with its own implementation. If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.

A derived class can hide base class members by declaring members with the same name and signature. The new modifier can be used to explicitly indicate that the member is not intended to be an override of the base member. The use of new is not required, but a compiler warning will be generated if new is not used

No comments:

Post a Comment