Does creating an instance of a child class create an instance of the parent class?
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();
}
}
c# .net
add a comment |
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();
}
}
c# .net
add a comment |
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();
}
}
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();
}
}
c# .net
c# .net
edited Nov 21 at 6:48
Peter Mortensen
13.4k1983111
13.4k1983111
asked Nov 20 at 15:01
brk
14825
14825
add a comment |
add a comment |
7 Answers
7
active
oldest
votes
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.
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
@brk well... both yes and no; if we create an instance of typeDog
, and ask what it is (GetType()
): it will sayDog
; however, allDog
s are animals, so it is true to say thatdogInstance is Animal
. We haven't created anew Animal()
instance that only knows aboutAnimal
, though. In fact,Animal
could beabstract
(and probably should be)
– Marc Gravell♦
Nov 20 at 15:09
3
@brk to put it another way: it isn't implemented as though theDog
instance had a private field that isAnimal _baseTypeInstance;
- there is only oneobject
here, and as far as it is concerned: it is aDog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
add a comment |
No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base() // base() call is voluntary
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
However if your base class didn't have a parameterless constructor you would have to call it
class Program
{
public class ParentClass
{
public ParentClass(string foo)
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base("some foo") // base call is obligatory
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
By definition when ChildClass
inherits form ParentClass
, then ChildClass
objects belong to the ParentClass
as well.
If your naming was more real-life oriented, it would be easier to understand.
class Animal {}
class Cat : Animal {}
var rocky = new Cat();
See, rocky is a cat, but it is an animal as well.
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.
– Andrzej Gis
Nov 20 at 15:54
add a comment |
The actual answer to your question is
'No', it is an instance of the Child class, not of the Parent.
But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is
'Yes', you will have all properties and fields that you have in the
Parent class copied into the Child instance.
add a comment |
Talking specifically about your code:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ParentClass constructor is called");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("ChildClassConstructor is called");
}
}
public static void Main()
{
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ChildClass child = new ChildClass();
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ParentClass childinparentbox = new ChildClass();
//will print that the Parent ctor is called
ParentClass parent = new ParentClass();
//At this point there are 3 object instances in memory
//by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
ChildClass parentinchildbox = new ParentClass();
}
}
I changed the messages to make them relevant to the point being made:
A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent
As others have noted, you don't get multiple instances of objects when you use new
, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.
So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.
One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".
Getting back to what you asked:
Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent
So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child
It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order
add a comment |
No it will only create an instace of the child class.
add a comment |
Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
add a comment |
let say you have Parent Class Coffee
and Child Class Cappucino
class Coffee {}
class Cappucino : Coffee {}
by issuing new Cappucino()
, an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.
No seperate instance is created for Coffee.
Cappucino carries features of Coffee by inheritance
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395800%2fdoes-creating-an-instance-of-a-child-class-create-an-instance-of-the-parent-clas%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
@brk well... both yes and no; if we create an instance of typeDog
, and ask what it is (GetType()
): it will sayDog
; however, allDog
s are animals, so it is true to say thatdogInstance is Animal
. We haven't created anew Animal()
instance that only knows aboutAnimal
, though. In fact,Animal
could beabstract
(and probably should be)
– Marc Gravell♦
Nov 20 at 15:09
3
@brk to put it another way: it isn't implemented as though theDog
instance had a private field that isAnimal _baseTypeInstance;
- there is only oneobject
here, and as far as it is concerned: it is aDog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
add a comment |
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.
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
@brk well... both yes and no; if we create an instance of typeDog
, and ask what it is (GetType()
): it will sayDog
; however, allDog
s are animals, so it is true to say thatdogInstance is Animal
. We haven't created anew Animal()
instance that only knows aboutAnimal
, though. In fact,Animal
could beabstract
(and probably should be)
– Marc Gravell♦
Nov 20 at 15:09
3
@brk to put it another way: it isn't implemented as though theDog
instance had a private field that isAnimal _baseTypeInstance;
- there is only oneobject
here, and as far as it is concerned: it is aDog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
add a comment |
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.
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.
answered Nov 20 at 15:03
Marc Gravell♦
776k19121252537
776k19121252537
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
@brk well... both yes and no; if we create an instance of typeDog
, and ask what it is (GetType()
): it will sayDog
; however, allDog
s are animals, so it is true to say thatdogInstance is Animal
. We haven't created anew Animal()
instance that only knows aboutAnimal
, though. In fact,Animal
could beabstract
(and probably should be)
– Marc Gravell♦
Nov 20 at 15:09
3
@brk to put it another way: it isn't implemented as though theDog
instance had a private field that isAnimal _baseTypeInstance;
- there is only oneobject
here, and as far as it is concerned: it is aDog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
add a comment |
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
@brk well... both yes and no; if we create an instance of typeDog
, and ask what it is (GetType()
): it will sayDog
; however, allDog
s are animals, so it is true to say thatdogInstance is Animal
. We haven't created anew Animal()
instance that only knows aboutAnimal
, though. In fact,Animal
could beabstract
(and probably should be)
– Marc Gravell♦
Nov 20 at 15:09
3
@brk to put it another way: it isn't implemented as though theDog
instance had a private field that isAnimal _baseTypeInstance;
- there is only oneobject
here, and as far as it is concerned: it is aDog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
Nov 20 at 15:06
4
4
@brk well... both yes and no; if we create an instance of type
Dog
, and ask what it is (GetType()
): it will say Dog
; however, all Dog
s are animals, so it is true to say that dogInstance is Animal
. We haven't created a new Animal()
instance that only knows about Animal
, though. In fact, Animal
could be abstract
(and probably should be)– Marc Gravell♦
Nov 20 at 15:09
@brk well... both yes and no; if we create an instance of type
Dog
, and ask what it is (GetType()
): it will say Dog
; however, all Dog
s are animals, so it is true to say that dogInstance is Animal
. We haven't created a new Animal()
instance that only knows about Animal
, though. In fact, Animal
could be abstract
(and probably should be)– Marc Gravell♦
Nov 20 at 15:09
3
3
@brk to put it another way: it isn't implemented as though the
Dog
instance had a private field that is Animal _baseTypeInstance;
- there is only one object
here, and as far as it is concerned: it is a Dog
– Marc Gravell♦
Nov 20 at 15:10
@brk to put it another way: it isn't implemented as though the
Dog
instance had a private field that is Animal _baseTypeInstance;
- there is only one object
here, and as far as it is concerned: it is a Dog
– Marc Gravell♦
Nov 20 at 15:10
Thank you guys for the infos
– brk
Nov 20 at 15:12
Thank you guys for the infos
– brk
Nov 20 at 15:12
11
11
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas
Nov 21 at 8:22
add a comment |
No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base() // base() call is voluntary
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
However if your base class didn't have a parameterless constructor you would have to call it
class Program
{
public class ParentClass
{
public ParentClass(string foo)
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base("some foo") // base call is obligatory
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
By definition when ChildClass
inherits form ParentClass
, then ChildClass
objects belong to the ParentClass
as well.
If your naming was more real-life oriented, it would be easier to understand.
class Animal {}
class Cat : Animal {}
var rocky = new Cat();
See, rocky is a cat, but it is an animal as well.
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.
– Andrzej Gis
Nov 20 at 15:54
add a comment |
No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base() // base() call is voluntary
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
However if your base class didn't have a parameterless constructor you would have to call it
class Program
{
public class ParentClass
{
public ParentClass(string foo)
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base("some foo") // base call is obligatory
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
By definition when ChildClass
inherits form ParentClass
, then ChildClass
objects belong to the ParentClass
as well.
If your naming was more real-life oriented, it would be easier to understand.
class Animal {}
class Cat : Animal {}
var rocky = new Cat();
See, rocky is a cat, but it is an animal as well.
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.
– Andrzej Gis
Nov 20 at 15:54
add a comment |
No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base() // base() call is voluntary
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
However if your base class didn't have a parameterless constructor you would have to call it
class Program
{
public class ParentClass
{
public ParentClass(string foo)
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base("some foo") // base call is obligatory
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
By definition when ChildClass
inherits form ParentClass
, then ChildClass
objects belong to the ParentClass
as well.
If your naming was more real-life oriented, it would be easier to understand.
class Animal {}
class Cat : Animal {}
var rocky = new Cat();
See, rocky is a cat, but it is an animal as well.
No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base() // base() call is voluntary
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
However if your base class didn't have a parameterless constructor you would have to call it
class Program
{
public class ParentClass
{
public ParentClass(string foo)
{
Console.WriteLine("ChildClass drived from me ");
}
}
public class ChildClass : ParentClass
{
public ChildClass() : base("some foo") // base call is obligatory
{
Console.WriteLine("This also use my Ctor");
}
}
public static void Main()
{
ChildClass child = new ChildClass();
}
}
By definition when ChildClass
inherits form ParentClass
, then ChildClass
objects belong to the ParentClass
as well.
If your naming was more real-life oriented, it would be easier to understand.
class Animal {}
class Cat : Animal {}
var rocky = new Cat();
See, rocky is a cat, but it is an animal as well.
edited Nov 21 at 12:52
answered Nov 20 at 15:04
Andrzej Gis
6,57985297
6,57985297
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.
– Andrzej Gis
Nov 20 at 15:54
add a comment |
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.
– Andrzej Gis
Nov 20 at 15:54
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
Thank you that was useful, can you also please tell me why we can not do something like this: Animal dog = new Dog(); Dog ricky = dog; // cannot implicity convert Type "Animal" to "Dog"
– brk
Nov 20 at 15:27
3
3
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (
dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.– Andrzej Gis
Nov 20 at 15:54
@brk Because not every animal is a dog :). The "dog" variable in your code is of Animal type. Currently you have assigned a Dog to it. But you could've also assigned a Cat (
dog = new Cat()
). So compiler won't let you assign the "dog" (Aminal) to a Dog class. Unless you cast it (Dog ricky = (Dog)dog
) - this way you tell the compiler you know what you're doing and you're not accidentally assigning a Cat to a Dog. However if the "dog" is not a Dog, you will get an InvalidCastException.– Andrzej Gis
Nov 20 at 15:54
add a comment |
The actual answer to your question is
'No', it is an instance of the Child class, not of the Parent.
But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is
'Yes', you will have all properties and fields that you have in the
Parent class copied into the Child instance.
add a comment |
The actual answer to your question is
'No', it is an instance of the Child class, not of the Parent.
But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is
'Yes', you will have all properties and fields that you have in the
Parent class copied into the Child instance.
add a comment |
The actual answer to your question is
'No', it is an instance of the Child class, not of the Parent.
But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is
'Yes', you will have all properties and fields that you have in the
Parent class copied into the Child instance.
The actual answer to your question is
'No', it is an instance of the Child class, not of the Parent.
But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is
'Yes', you will have all properties and fields that you have in the
Parent class copied into the Child instance.
answered Nov 20 at 15:11
Mayer Spitzer
561314
561314
add a comment |
add a comment |
Talking specifically about your code:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ParentClass constructor is called");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("ChildClassConstructor is called");
}
}
public static void Main()
{
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ChildClass child = new ChildClass();
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ParentClass childinparentbox = new ChildClass();
//will print that the Parent ctor is called
ParentClass parent = new ParentClass();
//At this point there are 3 object instances in memory
//by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
ChildClass parentinchildbox = new ParentClass();
}
}
I changed the messages to make them relevant to the point being made:
A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent
As others have noted, you don't get multiple instances of objects when you use new
, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.
So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.
One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".
Getting back to what you asked:
Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent
So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child
It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order
add a comment |
Talking specifically about your code:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ParentClass constructor is called");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("ChildClassConstructor is called");
}
}
public static void Main()
{
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ChildClass child = new ChildClass();
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ParentClass childinparentbox = new ChildClass();
//will print that the Parent ctor is called
ParentClass parent = new ParentClass();
//At this point there are 3 object instances in memory
//by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
ChildClass parentinchildbox = new ParentClass();
}
}
I changed the messages to make them relevant to the point being made:
A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent
As others have noted, you don't get multiple instances of objects when you use new
, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.
So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.
One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".
Getting back to what you asked:
Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent
So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child
It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order
add a comment |
Talking specifically about your code:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ParentClass constructor is called");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("ChildClassConstructor is called");
}
}
public static void Main()
{
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ChildClass child = new ChildClass();
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ParentClass childinparentbox = new ChildClass();
//will print that the Parent ctor is called
ParentClass parent = new ParentClass();
//At this point there are 3 object instances in memory
//by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
ChildClass parentinchildbox = new ParentClass();
}
}
I changed the messages to make them relevant to the point being made:
A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent
As others have noted, you don't get multiple instances of objects when you use new
, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.
So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.
One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".
Getting back to what you asked:
Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent
So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child
It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order
Talking specifically about your code:
class Program
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("ParentClass constructor is called");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("ChildClassConstructor is called");
}
}
public static void Main()
{
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ChildClass child = new ChildClass();
//will print that the Parent ctor is called, followed by printing that the child ctor is called
ParentClass childinparentbox = new ChildClass();
//will print that the Parent ctor is called
ParentClass parent = new ParentClass();
//At this point there are 3 object instances in memory
//by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
ChildClass parentinchildbox = new ParentClass();
}
}
I changed the messages to make them relevant to the point being made:
A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent
As others have noted, you don't get multiple instances of objects when you use new
, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.
So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.
One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".
Getting back to what you asked:
Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent
So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child
It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order
edited Nov 21 at 14:12
answered Nov 21 at 14:06
Caius Jard
9,41611137
9,41611137
add a comment |
add a comment |
No it will only create an instace of the child class.
add a comment |
No it will only create an instace of the child class.
add a comment |
No it will only create an instace of the child class.
No it will only create an instace of the child class.
answered Nov 20 at 15:05
Sr.Mento
212
212
add a comment |
add a comment |
Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
add a comment |
Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
add a comment |
Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
edited Dec 4 at 11:44
answered Nov 22 at 12:55
Jamiel Thomas
112
112
add a comment |
add a comment |
let say you have Parent Class Coffee
and Child Class Cappucino
class Coffee {}
class Cappucino : Coffee {}
by issuing new Cappucino()
, an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.
No seperate instance is created for Coffee.
Cappucino carries features of Coffee by inheritance
add a comment |
let say you have Parent Class Coffee
and Child Class Cappucino
class Coffee {}
class Cappucino : Coffee {}
by issuing new Cappucino()
, an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.
No seperate instance is created for Coffee.
Cappucino carries features of Coffee by inheritance
add a comment |
let say you have Parent Class Coffee
and Child Class Cappucino
class Coffee {}
class Cappucino : Coffee {}
by issuing new Cappucino()
, an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.
No seperate instance is created for Coffee.
Cappucino carries features of Coffee by inheritance
let say you have Parent Class Coffee
and Child Class Cappucino
class Coffee {}
class Cappucino : Coffee {}
by issuing new Cappucino()
, an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.
No seperate instance is created for Coffee.
Cappucino carries features of Coffee by inheritance
answered Dec 10 at 13:10
Simonare
3,100726
3,100726
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395800%2fdoes-creating-an-instance-of-a-child-class-create-an-instance-of-the-parent-clas%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown