Introducation to Inheritance in C#

t5j9033387989
Posted by t5j9033387989 under C# category on | Points: 40 | Views : 1853
As inheritance is used when a class is build upon another class .In the term of data or behavior and it adheres to the rules of substitutability namely, that the derived class can be substituted for the base class .
An example of this would be if you were writing a hierarchy of application class you want to have a class for handing member A application member B application. Assume these applications differ in some respect you had wanted to a class for each application. However both application dp share enough functionality that you would want to put the common functionality into a base class, derive the other two classes from the base class , and override or modify the inherited base class behavior at times.
To the inherit one class form another, you would use the following syntax:

Class derived class:base class


Here is what this application example would look like:

Using system;
Class application
{
Public application()
{
commonField=100;
}
Public int commonfield;
Public void commonmethod()
{
Console.WriteLine("application.Common Method");
}
}
Class MemeberA : application
{
Public void SomeMethodSpecificToMemberA()
{
Console.WriteLine("MemberA. SomeMethodSpecificToMemberA")
}
}
Class MemeberB : application
{
Public void SomeMethodSpecificToMemberB()
{
Console.WriteLine("MemberB. SomeMethodSpecificToMemberB")
}
}
Class InheritanceApp
{
Public static void main()
{
MemberA MemberA= new MemberA();

MemberA. SomeMethodSpecificToMemberA();
MemberA.CommonMethod();
Console.WriteLine("Inherited common field={0}",memberA.CommonField);
}
}


Compiling and excuting this appilication result in the following output"
MemberA. SomeMethodSpecificToMemberA
Application. Common Method
Inherited common field = 42
Example of Inheritance


class App
{
static void Main(string[] args)
{
A obj = new B();
obj.Show();
Console.ReadLine();
}
}
class A
{
public virtual void Show()
{
Console.WriteLine("A.Show()");
}
}
class B : A
{
public override void Show()
{
Console.WriteLine("B.Show()");
}
}



RESULT

B.Show()

Comments or Responses

Login to post response