Click here to Skip to main content
15,900,108 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public class A
   {
       public A()
       {
           Console.WriteLine("A");
       }

   }
   public class B : A
   {
       public B()
       {
           Console.WriteLine("B");

       }
       public void method1()
       {
           Console.WriteLine("BM1");
       }
   }

class Program
   {
       static void Main(string[] args)
       {
           A obj = new B();// what is use of it?
           obj.method();
           Console.Read();
       }
       private void methodP1()
       {

       }
   }
Posted

That means you are having a variable "obj" which is of type A. Then at Right Hand Side, you are creating an instance of B and assigning it into variable "obj". Since B is inherited from A so it is possible without casting.

Now while using variable "obj", you will get only methods which belongs to A (either direct methods written in A or overridden by B depends on situation).

Thanks.
 
Share this answer
 
v2
By using A obj = new B(); a new object of class B is created and assigned to variable obj. This variable is actually of type class A. However, B is derived from A and this will work.

A super class reference variable can hold reference of sub-class object without casting.
 
Share this answer
 
v2
A obj = new B();
you're constructing an object obj that can do the job of either a B or a A.
B is inherited from A. This way you can access all the properties and methods of A.


And found this here[^]:
This is the basis for polymorphism: Imagine you have several child classes that inherit from you parent class. You want to use all these child classes through the interface / methods defined on your parent class, without worrying about the implementation details in each child class (each might do something different, but with the same overall semantics).

This is possible because the child class has a IS-A relationship with its parent class since child inherits from parent.

I'd suggest you to learn Inheritance & Polymorphism,
https://www.cs.utexas.edu/~scottm/cs307/handouts/InheritanceExplanation.htm[^]
http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx[^]


-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900