Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does creating an instance of a child class create an instance of the parent class?

Tags:

c#

.net

I'm new to C#, and I wanted to know, that if I create an instance of a child class, does it also automatically create an instance of the parent class or what?

Here is my code:

class Program {      public class ParentClass     {         public ParentClass()         {             Console.WriteLine("ChildClass uses my Ctor ");         }      }      public class ChildClass : ParentClass     {         public ChildClass()         {             Console.WriteLine("SaySomething");         }     }      public static void Main()     {         ChildClass child = new ChildClass();     } } 
like image 574
brk Avatar asked Nov 20 '18 15:11

brk


People also ask

Is the child class instance an instance of the parent class?

Every instance of a child class has an instance of a parent class.

Can a child class create object of parent class?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.

Can we create instance of parent class?

To explain in simple language, parents create child ( or give birth to them) child do not create parent. Since OOPs takes concepts from real world entities it is wrong for a child to create its parent. compiler will think you are calling method from class Pqr.

Can a child class also be a parent class?

No, you can not do. This is because any instance of ClassB is also an instance of ClassA but vice versa is not true.


1 Answers

does it also automatically create an instance of the Parent class?

Not a separate instance; the ChildClass is a ParentClass instance, when talking about inheritance.

In words, this is like:

when creating a dog, do we also create an instance of an animal?

We don't create a dog and (separately) create an animal; the dog is the animal instance. And if we create a poodle, the poodle is the dog and is the animal.

like image 141
Marc Gravell Avatar answered Sep 20 '22 12:09

Marc Gravell