Posted: 10/25/2010
I am newbie in C#.I have one confusion.There are two classes A and B.using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { A objA = new A(); A objB = new B(); } } class A { public void MethodA() { Console.WriteLine("method of A class"); } } class B : A { public void MethodB() { Console.WriteLine("method of B class"); } } }
I am newbie in C#.I have one confusion.
There are two classes A and B.
using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { A objA = new A(); A objB = new B(); } } class A { public void MethodA() { Console.WriteLine("method of A class"); } } class B : A { public void MethodB() { Console.WriteLine("method of B class"); } } }
Now the confusion which I have is that what is the meaning of:
A objB = new B();
I have seen and instantiated class like this:
A objB = new A();
Can anyone tell me why we used:
Thanks in advance.
Mohit, you have some really challenging and interesting questions :) -
Here is how I think you will understand this best.
I've rewritten your code so that I've added constructors in each class. Run it and see the difference and what ideas will come to you once you see the printed result.
class Program { static void Main(string[] args) { Console.WriteLine("---------- A objB = new B(); -------------"); A objB = new B(); objB.MethodA(); Console.WriteLine(Environment.NewLine); Console.WriteLine("---------- A objB = new A(); -------------"); A objA = new A(); objA.MethodA(); Console.ReadLine(); } } class A { public A() { Console.WriteLine("Constructor of class A"); } public void MethodA() { Console.WriteLine("method of A class"); } } class B : A { public B() { Console.WriteLine("Constructor of class B"); } public void MethodB() { Console.WriteLine("method of B class"); } }
hajan said: user="Hajan Selmani"]Mohit, you have some really challenging and interesting questions :) -
user="Hajan Selmani"]Mohit, you have some really challenging and interesting questions :) -
Thank you Hajan
Check my code now -
using System; class Program { static void Main(string[] args) { Console.WriteLine("---------- A objB = new B(); -------------"); A objB = new B(); objB.MethodA(); Console.WriteLine(Environment.NewLine); Console.WriteLine("---------- A objB = new A(); -------------"); B objA = new B(); objA.MethodA(); Console.ReadLine(); } } class A { public A() { Console.WriteLine("Constructor of class A"); } public void MethodA() { Console.WriteLine("method of A class"); } } class B : A { public B() { Console.WriteLine("Constructor of class B"); } public void MethodB() { Console.WriteLine("method of B class"); } }
The difference is that now you have both methods accessible to the objA
B objA = new B()
objA.MethodA(); //accessibleobjA.MethodB(); //accessible
previously you didn't have both of them, now you do since B inherits all the objects from A.
I hope it's clear now :)