Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CSharp.NET Tutorial – Day 11


In previous article, we have discussed how to work with Visual Studio along with some important components like Solution Explorer, etc, what is Namespace, a brief on Object Oriented Programming, what is the drawback in Procedural Programming approach i.e. Security and Reusability of the code, features of object oriented programming like Encapsulation, Abstraction, Inheritance, Polymorphism, what are Subprograms, what are methods, what are Modifiers available like public, private, internal, virtual, static, what are Input parameters and Output parameters, what is difference between passby value and passby reference, what are ref and out keywords, what is Constructor, what are Zero Argument (or) Default Constructors and Parameterized Constructors, what is Static, what are Non-static (or) Instance Methods and Static members, what are Instance variables and Static Variables and difference between Instance variables and Static Variables, what are Constant Variables, what are ReadOnly Variables, difference between Constant Variables and ReadOnly Variables, what are Static Methods and Instance Methods, difference between Static Methods and Instance Methods, what are Static Constructors and Instance Constructors, difference between Static Constructors and Instance Constructors, what are Static Classes along with syntaxes and some examples for better understanding, etc

Please find below the link for accessing the article
CSharp.NET Tutorial - Day 10 

Now, in this article we will discuss what is Inheritance, what are the rules and regulations to be adopted when we are working with Inheritance, what are different Types of Inheritance like Single Inheritance, Multiple Inheritance, etc, how to work with parent class constructors and Child Class constructors, How to consume a class from other classes using Inheritance and By creating the object of class, what are Extension Methods, How to Define Extension Methods, what is Polymorphism, what is Method Overloading, what is Constructor Overloading, what is Operator Overloading, what is Inheritance Based Overloading, what is Method Overriding, Differences between Overloading and Overriding, How to Override Parent class’s Method under Child class, What happens when we override Parent class’s virtual methods under child class, what is Method Hiding, what are different types of Polymorphism like Static (or) Compile time Polymorphism and Dynamic (or) Runtime Polymorphism, what is Operator Overloading, what are Sealed Classes and Sealed Methods along with syntaxes and some examples for better understanding, etc

Inheritance
We can define Inheritance as “the members which are defined in a class can be consumed from another class.”  To achieve this, first we need to create parent-child relationship in between the old class and the new class.



Syntax

[<Modifiers>] class <Child Class Name> : <Parent Class Name>

Eg:

class Class1
{
-Members
}

class Class2 : Class1
{
-Consume Members of its parent
}

Note:  The default scope for Members of a class in C# is “private” and “private” members of a class cannot be consumed under child classes.

Add a class “Class1.cs” and write the below code.

class Class1
{
public Class1()
{
Console.WriteLine ("Class1 Constructor");
}
public void Test1()
{
Console.WriteLine ("Method one");
}
public void Test2()
{
Console.WriteLine ("Method two");
}
}

Add a class “Class2.cs” and write the below code.

class Class2
{
public Class2()
{
Console.WriteLine("Class2 Constructor");
}
public void Test3()
{
Console.WriteLine("Method three");
}
static void Main()
{
Class1 c = new Class1();
Class2 f= new Class2();
c.Test1(); c.Test2(); f.Test3();
Console.ReadLine();
}
}

There are some rules and regulations to be adopted when we are working with Inheritance
Rule 1:  In inheritance, Constructor of parent class should always be accessible to its child classes.  It is because execution of a child class starts by invoking default Constructor of its parent class.  If it is not accessible means inheritance is not possible.

Rule 2:  Child class can access members of its parent class, whereas parent classes cannot access child class members, which is against the rules of inheritance.

To test this, rewrite the code under Main method of child class ‘class2’ as below.

Class1 p=new Class1 ();
p.Test1 ();p. Test2 ();
//p.Test3 (); --> Invalid (Error)
Console.ReadLine ();

Rule 3:  We have discussed earlier that object of a class can be assigned to a variable of the same class and make it as a reference.  In the same way, object of a class can be assigned to its parent class variable also to make it as reference.  Once the assignment is done, both child class object and parent class reference will be consuming the same memory.  But here also using parent’s reference, invoking child members is not possible.

To test this, rewrite the code under the child class Main method as below.

Class2 c=new Class2();
Class1 p=c;
p.Test1();p.Test2();
p.Test3(); //Invalid(Error)
Console.ReadLine();

Note:  If required, the reference of a parent class created using object of a child class can be converted back into child class’s reference by using explicit type casting process.

Step1:  Create object of child class
Class2 c=new Class2();

Step2:  Create reference of parent class using object of Child class
Class1 p=c;

Step3:  Convert parent class reference using object of child class back in child class reference
Class2 c2=p as Class2();

or

Class2 c2=(Class2)p;

Rule 4:  Every class that is defined in .NET languages must inherit from a pre-defined class ‘object’ under the system namespace within Base Class Libraries.  So internally every class will be implicitly inherited from ‘object’ class either directly or indirectly.  So we can access members of ‘object’ class like GetType, ToString, GetHashCode, Equals, etc from any class which is defined by us (or) in predefined classes.

To test this, rewrite the code under Main method of child class, ‘Class2’ as below.

Object obj=new Object ();
Console.WriteLine (obj.GetType ());
Class1 p=new Class1 ();
Console.WriteLine (p.GetType ());
Class2 c=new Class2 ();
Console.WriteLine (c.GetType ());
Console.ReadLine ();

Types of Inheritance
As per the standards of object oriented programming, we are provided with two different types of Inheritance
1) Single Inheritance
2) Multiple Inheritance

If a class is having only one immediate parent class to it we call it as Single inheritance, whereas if it has more than one immediate parent classes we call it as Multiple Inheritance.

Based on these two inheritances, we can create different types of inheritances as in below diagram.





Rule 5:  Both in Java and .NET Languages, we are not given the support for Multiple Inheritance through classes because it suffers from ambiguity problem i.e. same member can be defined in multiple parent classes.

Rule 6:  As we have discussed earlier that when we create an object of a child class, it will first implicitly invoke parent class’s default Constructor, but sometimes parent classes can be defined with a parameterized Constructor without any default Constructor.  In such scenarios, implicit calling of the parent class Constructor will not be possible because the parent class requires a value for execution.

To resolve the above problem, it is the programmer’s responsibility to explicitly call parent class parameterized Constructor from the child class Constructor by sending required values to the parameter using the keyword ‘base’ which refers to a parent class.

To test this, make the below changes

a) Goto the class ‘Class1’ and rewrite its constructor as below.

public Class1(int x)
{
Console.WriteLine("Class1 Constructor:"+x);
}

Now try to run the child class where we will get an error at child class Constructor stating Class1 does not contain a parameter less Constructor in it.

To resolve the problem, rewrite the Constructor of ‘Class2’ as below.

public Class2(int x,int y) : base(x)
{
Console.WriteLine("Class2 Constructor:"+y);
}

Now while creating object of child class under the main method of ‘class2,’ we need to send values to parameters of its Constructor as below.

Class2 = new Class2(10,20);

How to consume a class from other classes
There are two different ways that we can consume a class from other classes.
1) Using Inheritance
2) By creating the object of class

To test the second process, add new class as “Class3.cs” and write the below code

class Class3
{
static void Main()
{
Class1 obj = new Class1 (30);
obj.Test1 (); obj.Test2 ();
Console.WriteLine ();
}
}

Extension Methods
This is a new feature which has been added in C#3.0.  It allows us to add methods under a class without editing its source code.

The concept of extension methods is near similar to the concept of inheritance.  In inheritance, we can extend the functionalities of a class by defining a child class to it, whereas in case of extension methods also new methods can be added to a class by defining the methods under a new class which should be of type ‘static’ and then can be bound with the class to which we want to add the methods.

How to Define Extension Methods
a) We can define an Extension method only under a ‘static’ class.
b) As we define them under static classes, we need to define them as static.  But once they are bound to a class, those will be treated as Instance Methods and should be accessed using object of the class.
c) An Extension Method should have a Mandatory Parameter that is the name of the class to which they are going to bound prefixed with ‘this’ keyword.  This parameter should not be considered while calling the method.
d) An Extension Method can be bound with single class only.

Add a class ‘Original.cs’ and write the below code

class Original
{
public int x = 50;
public void Show1()
{
Console.WriteLine ("Method1:" + this.x);
}
public void Show2()
{
Console.WriteLine ("Method2");
}
}

Add a class ‘StatClass.cs’ and write the below code making the class as static

static class StatClass
{
public static void Show3(this Original obj)
{
Console.WriteLine ("Method3");
}
public static void Show4 (this Original obj,int x)
{
Console.WriteLine ("Method4:"+x);
}
public static void Show5 (this Original obj)
{
Console.WriteLine ("Method5:"+obj.x);
}
}

Add new class ‘TestOriginal.cs’ and write the below code in it

class TestOriginal
{
static void Main()
{
Original obj = new Original ();
obj.Show1 (); obj.Show2 (); obj.Show3 ();
obj.Show4 (); obj.Show5 ();
Console.ReadLine ();
}
}

Polymorphism

Polymorphism can be defined as “entities behave in different ways based on the input they received” i.e. the behavior of the entities can be changed with a change in input that we supply to them.  This can be implemented in Object Oriented Programming languages using the concepts ‘overloading,’ ‘overriding’ and ‘hiding.’  We will discuss all these one by one.  First we will start with Overloading.


Overloading
There are three types of Overloading available which are as follows.
1) Method Overloading
2) Constructor Overloading
3) Operator Overloading

1) Method Overloading
Method Overloading allows us to define multiple methods in a class with same name but change in their signatures.  It means we can change the number of parameters that is being passed to the Method (or) type of parameters being passed to the Method (or) Order of parameters being passed to the Method.


Eg:
public void Show()
public void Show(int x)
public void Show(string s)
public void Show(int x, string s)
public void Show(string s, int x)

Note:  In overloading, a change in return type of parameter will not be taken into consideration.

Eg:
public string Show() //Invalid

Overloading is an approach which allows us to define multiple behaviors to a Method.

For example, WriteLine method of the Console class given with 19 different behaviors that is capable to print any type of value supply to it, which are implemented as below.

WriteLine ()
WriteLine (int value)
WriteLine (string value)
WriteLine (float value)

To test this, add a class “LoadEx.cs” and write the below code

class LoadEx
{
public void Show()
{
Console.WriteLine (1);
}
public void Show(int x)
{
Console.WriteLine (2);
}
public void Show(string s)
{
Console.WriteLine (3);
}
public void Show(int x, string s)
{
Console.WriteLine (4);
}
public void Show(string s, int x)
{
Console.WriteLine (5);
}
static void Main()
{
LoadEx obj = new LoadEx ();
obj.Show ();
obj.Show (10);
obj.Show ("Hello");
obj.Show (10, "Hello");
obj.Show ("Hello", 10);
Console.ReadLine ();
}
}

2) Constructor Overloading
Just like Method Overloading, we can also overload constructer of a class also.  If a class is defined with multiple constructors, any constructor can be used to create object of that class.  Overloading of constructors allows us to initialize the variables of a class either by using default values with different constructors or we can also initialize them with a set of values that are sent using the constructor while creating the object.

To test this, add a class “LoadCon.cs” and write the below code

class LoadCon
{
int x;
public LoadCon()
{
//Initializing with a default value
x = 10;
}
public LoadCon(int x)
{
//Initializing a value dynamically
this.x = x;
}
public void Display()
{
Console.WriteLine (" x value is :{ 0}", x);
}
static void Main()
{
LoadCon c1 = new LoadCon ();
LoadCon c2 = new LoadCon (10);
c1.Display ();
c2.Display ();
Console.ReadLine ();
}
}

In the above program, the variable ‘x’ of a class is initialized with a default value of 10 when the object of class is created using default constructor, whereas it is initialized with the value what we send when the object is created using parameterized constructor.

Inheritance Based Overloading
If a method of parent class is overloaded under its child class, we call it as Inheritance Based Overloading.  So it means methods can be overloaded either within the class or within the child class also.

Eg:

class LoadParent
{
public void Show()
}
class LoadChild : LoadParent
{
public void Show(string s)
}

Add a class “LoadParent.cs” and write the below code in it

class LoadParent
{
public void Show()
{
Console.WriteLine("Parent Show Method1");
}
public void Test()
{
Console.WriteLine("Parent Test Method1");
}
public void Display()
{
Console.WriteLine("Parent Display Method1");
}
}

Add a class "LoadChild.cs" and write the below code in it
class LoadChild:LoadParent
{
//Overloading Show method under child class
public void Show(string s)
{
Console.WriteLine("Child Show Method2");
}
static void Main()
{
LoadChild c=new LoadChild();
c.Show(); //Invokes parent class Method
c.Show("Hello"); //Invokes Child class Method
Console.ReadLine();
}
}

Method Overriding
If a Method defined in a class is redefined under its child class with the same signature, we can call it as Method Overriding.


Differences between Overloading and Overriding

Overloading
Overriding
It allows defining of multiple methods with the same name but change in their signature.
It allows defining of multiple methods with the same name with the same signature.
This can be done within a class as well as child class also.
This can be done only under child class.
To overload parent class method under child class, we do not require any permission from parent.
To override Parent class under child class, we do require an explicit permission from Parent.
This is all about defining multiple behaviors to a method.
This is all about changing behavior of parent under Child class.

How to Override Parent class’s Method under Child class
If we want to override a parent class method under child class, first we should be declared the parent class method using “virtual” modifier.  Then, child class gets permission to override the method that can be done by child class using “override” modifier.

Eg:
class LoadParent
{
public virtual void Test()
}
class LoadChild : LoadParent
{
public override void Test()
}

Note:  Overriding virtual method declared in parent class under child class is only “optional”.

What happens when we override Parent class’s virtual methods under child class?
If parent class’s virtual method is overridden under child class, we can invoke the local methods using child class object that is overridden method of child class in place of virtual method of parent class.

To test this, do the following steps

Step 1:  Go to the class, LoadParent and add “virtual” modifier to the method “Test”

public virtual void Test()
Step 2:  Now come to the class, “LoadChild” and call the Test method using child class object under Main

LoadChild c=new LoadChild ();
c.Test (); //Invokes Parent class Method
Console.ReadLine ();

Run the above program and check the output, which also proves Overriding virtual methods of parent class under child class is only optional.

Step 3:  Now add new method under the class, LoadChild that overrides virtual method of parent class.

//Overriding Parent class Test method under child class
public override void Test()
{
Console.WriteLine ("Child Test Method2");
}

Now again when we run our child class and while checking the output, we will see the child class’s method getting called in the place of parent class now.

After overriding parent class’s virtual method under child class, we observed that object of child class is invoking local method only, but if required child class can still invoke parent class’s virtual methods also, which can be done in two different ways.

First Process
By creating object of parent class under child class, we can call parent class’s virtual methods from child class.

To test this, rewrite the code under child class Main method as below

LoadChild c=new LoadChild ();
LoadParent p=new LoadParent ();
p.Test (); //Invoking Parent Method
c.Test (); //Invoking Child Method
Console.ReadLine ();

Note:  Previously, we have discussed that reference of Parent class created using object of child class cannot invoke any child class method.  But here, we have a small exemption in case of ‘Method Overrriding’ i.e. parent class’s references can invoke virtual methods of the parent class that are overridden under child class because overriding is done with a permission of parent class.

To test this, rewrite the code under the child class Main method as below

LoadChild c=new LoadChild ();
LoadParent p=c;
p.Test(); //Invokes Child method only
c.Test(); //Invokes Child Method
Console.ReadLine();

Second Process
Using ‘base’ keyword also, we can invoke virtual methods of parent class from child class, but using ‘this’ and ‘base’ keywords from static block is not possible.

To test this, do the below

Add a new method under the child class, “LoadChild” as below

public void pTest()
{
base.Test ();
}

Now using the child class object, we can invoke the child class Method or Parent class Method from Main as below.

LoadChild c=new LoadChild ();
c.pTest (); //Invokes parent class Method
c.Test (); //Invokes child class Method
Console.ReadLine ();

Method Hiding
Parent class’s methods can be redefined under a child class using two different approaches.
1) Method Overriding
2) Method Hiding

In the first case, parent class gives permission to the child class to re-implement any of its Method by declaring the Method as “virtual,” which can be re-implemented under class using “override” modifier.

In the second case, parent class’s does not give any permission to child class to re-implement any of its methods, but still the child class can do it without parent class’s permission by using the operator “new” (optional)

class LoadParent
{
public void Display()
}
class LoadChild:LoadParent
{
public new void Display()
}

Whatever rules we discussed in case of overriding apply to Method Hiding also i.e. before redefining, child class object call the parent class method and after redefining, child class object call the Local Method.

To test this, rewrite the code under child class Main method as below

LoadChild c=new LoadChild ();
c.Display ();
Console.ReadLine ();

Run the above program and check the result which will execute the Display method of Parent class.

Now add a new method under child class, LoadChild as below

public new void Display()
{
Console.WriteLine ("Child Display Method2");
}

Now, again run the Child class and check the result and the result will be different.  Here, it invokes the new Method that we have defined.

Note:  We can invoke parent class’s Display method from a child class also like the two ways we have discussed in Method Overriding except reference of parent class created using object of Child class invoke parent class method only, but in Overriding child class Method is invoked.

We can test this by rewrite the code under child class under Main Method as below

LoadChild c=new LoadChild ();
LoadParent p=c;
p.Display ();
Console.ReadLine ();
class LoadParent
{
public void Show();
public virtual void Test();
public void Display();
}
class LoadChild:LoadParent
{
public void Show(string s) //Overriding
public override void Test() //Overriding
public new void Display() //Hiding
}

Basically, Polymorphism is of two types
1) Static (or) Compile time Polymorphism
2) Dynamic (or) Runtime Polymorphism


In Static (or) Compile time Polymorphism, the object of our class recognizes which polymorphism method we call at the time of compilation only.  It happens in case of overloading because here the method has different signatures though with the same method name.

Dynamic (or) Runtime Polymorphism, the object of class can recognize which polymorphism method it has to call only at the time of execution.  It happens in case of overriding and hiding because here multiple methods with the same name and same signature present.

Operator Overloading
Defining multiple behaviors to an operator is known as operator overloading.  For example, “+” is a overloaded operator that works as additional operator when used in between numeric values and works as an operator when used in between strings.

In the same way, we can also define any new behavior to our existing operators using the concept of operator overloading.

To overload an operator, first we need to define a method known as operator method as below

[<modifiers>] static <type> operator <opt>(<parameter definitions>)
{
statements;
}

Note:
-> An Operator Method must be static only
-> An Operator Method must be value-returning Method
-> The input and return type of an operator method will be of the same type

Add a class ‘Matrix.cs’ and write the below code

class Matrix
{
//Overloading variables for a 2*2 Matrix
int a,b,c,d;
public Matrix(int a,int b,int c,int d)
{
//Initializing the Matrix values
this.a=a; this.b=b;
this.c=c; this.d=d;
}

//Overloading * Operator to add 2 Matrix
public static Matrix operator +(Matrix m1,Matrix m2)
{
Matrix obj=new Matrix (m1.a+m2.a, m1.b+m2.b, m1.c+m2.c, m1.d+m2.d);
return obj;
}

//Overloading * operator to subtract 2Matrix
public static Matrix operator-(Matrix m1,Matrix m2)
{
Matrix obj=new Matrix (m1.a-m2.a, m1.b-m2.b, m1.c-m2.c, m1.d-m2.d);
return obj;
}

//Overloading ToString method of object class to print the value of Matrix
public override string ToString()
{
string str=String.Foramt("[a:{0};b:{1};c:{2};d:{3}]"a,b,c,d);
return str;
}
}

Add a new class, ‘TestMatrix.cs’ and write the below code

class TestMatrix
{
static void Main()
{
Matrix m1=new Matrix (5, 6, 7, 8);
Matrix m3=new Matrix (1, 2, 3, 4);
Matrix m3=m1+m2;
Matrix m4=m1-m2;
Console.WriteLine (m1);
Console.WriteLine (m2);
Console.WriteLine (m3);
Console.WriteLine (m4);
Console.ReadLine ();
}
}

Whenever we try to print the object of any class internally, the ‘ToString’ method of the ‘Object’ class gets called and prints the name of our class.

The method ‘ToString’ is a virtual method declared under object class, which can be override under any class because all classes are subclasses of the class ‘Object.’

Sealed Classes and Sealed Methods

Sealed Classes
A class which cannot be inherited by any other class is referred as a ‘Sealed’ class, but still we can consume the class by creating its object.

To make a class as ‘Sealed’ class, we should explicitly declare it using ‘sealed’ modifier

Eg:
sealed class Class1
{
-Members
}
Class Class2:Class1 //Invalid

Sealed Methods
A method which cannot be overridden by any child class is called ‘sealed’ method.  By default every method is a sealed method because overriding a method is not possible unless and until it is declared as virtual.

If any method is declared as virtual within a class, any child class in linear hierarchy has a chance to override the method.

class Class1
public virtual void Show()

class Class2:Class1
public override void Show()

class Class3:Class2
public override void Show()

If any child class wants to restrict its parent class’s virtual methods not be inherited by its child class while overriding the method, it can use the sealed modifier on the method like below.

class Class1
public virtual void Show()
class Class2:Class1
public override sealed void Show()
class Class3:Class2
public override void Show() //Invalid

Happy Learning ....... !!!!!

CSharp.NET Tutorial - Day 12


This post first appeared on Dot Net Programming (C#, Asp.Net, ADO.Net, WCF, WPF, Ajax, LINQ), please read the originial post: here

Share the post

CSharp.NET Tutorial – Day 11

×

Subscribe to Dot Net Programming (c#, Asp.net, Ado.net, Wcf, Wpf, Ajax, Linq)

Get updates delivered right to your inbox!

Thank you for your subscription

×