The following Code has been written in C#
Basic Virtual Method Overriding in the Child has been explained in the below code
1: using System;2: using System.Collections.Generic;3: using System.Linq;4: using System.Text;5:6: namespace Test7: {8: class Program9: {10: static void Main(string[] args)11: {12: // B Bobj = new A(); Correct13: A Aobj = new B();14: B Cobj = new B();15: A Dobj = new A();16:17: Aobj.MyPrint();18: Cobj.MyPrint();19: Dobj.MyPrint();20:21: }22: }23: public class A24: {25: public virtual void MyPrint()26: {27: Console.WriteLine("This method belongs to Class A");28: }29:30: }31: public class B : A32: {33: public override void MyPrint()34: {35: Console.WriteLine("This method belongs to Class B");36: }37: }38: }39:40:41: /*Output42: This method belongs to Class B43: This method belongs to Class B44: This method belongs to Class A45: */
Example 1: This is normal Basic Overriding concept
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: 6: namespace Test
7: {8: class Program
9: {10: static void Main(string[] args)
11: {12: // B Bobj = new A(); Correct
13: A Aobj = new B();
14: B Cobj = new B();
15: A Dobj = new A();
16: 17: Aobj.MyPrint(); 18: Cobj.MyPrint(); 19: Dobj.MyPrint(); 20: 21: } 22: }23: public class A
24: {25: public virtual void MyPrint()
26: {27: Console.WriteLine("This method belongs to Class A");
28: } 29: 30: }31: public class B : A
32: {33: public new void MyPrint()
34: {35: Console.WriteLine("This method belongs to Class B");
36: } 37: } 38: } 39: 40: 41: //Output
42: //This method belongs to Class A
43: //This method belongs to Class B
44: //This method belongs to Class AExample2: The shadowing concept in OOPs
Lets take the Example 1
“A Aobj =new B() ; Aobj.MyPrint()”;
Output:- This method belongs to Class B
And Lets take the Example 2
“A Aobj =new B() ; Aobj.MyPrint()”;
Output:- This method belongs to Class A
So why is the Output is different ?????
When you observe the Definition of B in Example 1
25: public virtual void MyPrint()
we are acutally OVERRIDEING so when you say “new B()” always you will be accessing the Method inside Class B.
But in Example 2 ,The definition of B is
33: public new void MyPrint()
This time shadowing is happening even you say new B() the childs method will be shadowed and you will be accessing the Parent method.

0 comments:
Post a Comment