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(); } }
Every instance of a child class has an instance of a 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.
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.
No, you can not do. This is because any instance of ClassB is also an instance of ClassA but vice versa is not true.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With