What is use of Parent object instantiating with child class

16,344

Solution 1

please tell me what is use of Parent obj = new Child(); as i we can only call to only public methods of parent class which is possible using Parent obj = new Parent();

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.

Solution 2

In your example, B is-a A, but A is-not-a B.

The above is of use when the code using the reference to B can only understand (or needs to understand) types of A. B is a specialisation of A. Imagine something like (pseudo-code)

Shape s;
if (x == 1) {
  s = new Square();
}
else {
  s = new Triangle();
}
// following code knows only about Shapes
s.draw();
s.calculateArea();

The following code doesn't need to know if s is a square or a triangle, just that it's a shape. What use is that ? If you call s.draw(), the shape itself determines how it's going to look. The code calling it doesn't know or care.

This is a key point of object-oriented programming. Asking objects to do things for you rather than determine yourself what's needed.

Note that your final question doesn't intuitively make sense when using this example.

Shape s = new Square(); // fine

vs

Square s = new Shape(); // can you instantiate a "shape" and why then do you decide it's a square?

Solution 3

BrokenGlass's answer is correct. However, your sample will have different behaviour depending upon whether you declare obj as type A or B.

In the case of A obj = new B(); the program will output A B AM because the compiler is linking to the virtual method A.method, which class B then inherits.

In the case of B obj = new B(); the program outputs A B BM because the compiler is directed to use the new method B.method().

If B.method() was instead declared as public override void method(), then the output would always be A B BM regardless of whether obj was declared as type A or type B.

Thus your example does not show polymorphism in the classic sense, as the method called on instances of type B depends on the type of the variable to which the instance is assigned. This can make debugging fun and interesting.

Solution 4

The reason that you would use polymorphism is so that you can pass a more specific object to an entity that only requires a more general object. The entity that receives the object only cares about the public interface that is exposed, not the details of how the methods in that interface are carried out. Here's a simple class hierarchy:

public class Animal
{
    public virtual string GetFood()
    {
        return "Food";         
    }
}

public class Monkey : Animal
{
    public override string GetFood()
    {
        return "Bananas";
    }
}

public class Cow : Animal
{
    public override string GetFood()
    {
        return "Grass";
    }
}

And here's how you could use the polymorphism:

class Program
{
    static void Main(string[] args)
    {
        Animal[] animalArray = { new Monkey(), new Cow() };
        foreach (Animal a in animalArray) {
            WhatDoIEat(a); // Prints "Bananas", then "Grass"
        }         
    }

    static void WhatDoIEat(Animal a)
    {
        Console.WriteLine(a.GetFood());
    }
}

Solution 5

If you have to use only the methods on the parent class, you can go ahead and instantiate it. The object of a child class is to add functionality to the parent class while keeping the parent intact. Instantiating the parent through the child without further use of the child functionality does not make sense.

Share:
16,344
Dr. Rajesh Rolen
Author by

Dr. Rajesh Rolen

Over 15 years of successful experience in development of multi-tier applications and system integration solutions as application architect, project leader, technical lead, and software engineer. Very good understanding of application analysis and design concepts. Strong ability to apply proven design patterns to the system design and employ extreme programming and SCRUM techniques to the robust implementations. PhD (Computer Science & Engineering), MCA, BCA, MCTS, MCP, SCJP. Experience of working in the complete Software development life cycle involving SRS, Software architecture design, database design, Code Reviews, development, and documentation. Capable to delve into the new leading Technologies. Ability to work well in both a team environment and individual environment. Ability to train the team. Areas of Expertise Strong in Architecture design, Design Principles, Design Patterns and OOPs concepts. Capable of developing cross-platform code and managing project. Web applications and web services development using ASP.NET MVC with C#.NET/ VB.NET. Client-Server based applications developed using C#.NET and VB.NET Strong in Business requirement analysis and functional specification design and documentation. Through knowledge of Object Oriented Analysis and Design OOAD and N - Tier Architecture Strong in front-end GUI development using ASP.Net, HTML, JavaScript, JQuery. Strong in backend database development including designing and administering databases, - writing stored procedures, SQL and triggers for SQL Server, Oracle, and My-SQL databases. Strong Analytical Skills. Strong oral and written communication skills Download CV

Updated on June 05, 2022

Comments

  • Dr. Rajesh Rolen
    Dr. Rajesh Rolen almost 2 years

    Please tell me what is of parent object instantiating with child class like:

     public class A
        {
            public A()
            {
                Console.WriteLine("A");
            }
            public virtual void method()
            {
                Console.WriteLine("AM");
            }
    
        }
        public class B : A
        {
            public B()
            {
                Console.WriteLine("B");
    
            }
            public new void method()
            {
                Console.WriteLine("BM");
    
            }
            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()
            {
    
            }
        }
    

    please tell me what is use of Parent obj = new Child(); as i we can only call to only public methods of parent class which is possible using Parent obj = new Parent();

    is it possible: Child obj = new Parent() ?

  • Banago
    Banago almost 13 years
    If all you need to use is the functions of the parent class, you do not need to instantiate it through a child class.
  • BillW
    BillW over 8 years
    "you can show other users that you are using a List and then you have the choice to implement the List as a LinkedList or as an ArrayList. " What are you talking about ? You imply you can defer specifying the Type of the List ?