Does creating an instance of a child class create an instance of the parent class?
up vote
16
down vote
favorite
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 |
up vote
16
down vote
favorite
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 |
up vote
16
down vote
favorite
up vote
16
down vote
favorite
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 yesterday
Peter Mortensen
13.3k1983111
13.3k1983111
asked 2 days ago
brk
984
984
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
up vote
48
down vote
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
2 days ago
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♦
2 days ago
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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
add a comment |
up vote
7
down vote
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
2 days ago
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
2 days ago
add a comment |
up vote
6
down vote
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 |
up vote
0
down vote
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 |
up vote
0
down vote
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 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.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
New contributor
add a comment |
up vote
-1
down vote
No it will only create an instace of the child class.
New contributor
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
48
down vote
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
2 days ago
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♦
2 days ago
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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
add a comment |
up vote
48
down vote
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
2 days ago
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♦
2 days ago
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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
add a comment |
up vote
48
down vote
up vote
48
down vote
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 2 days ago
Marc Gravell♦
770k19021172529
770k19021172529
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
2 days ago
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♦
2 days ago
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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
add a comment |
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
2 days ago
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♦
2 days ago
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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
2 days ago
so if i understood correctly, basicly we craete an instance of Animal class right?
– brk
2 days ago
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♦
2 days ago
@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♦
2 days ago
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♦
2 days ago
@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♦
2 days ago
Thank you guys for the infos
– brk
2 days ago
Thank you guys for the infos
– brk
2 days ago
9
9
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
Real life analogy: if you bought a dog, did you also buy an animal? Yes but not an entire seperate animal.
– Thomas Moors
yesterday
add a comment |
up vote
7
down vote
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
2 days ago
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
2 days ago
add a comment |
up vote
7
down vote
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
2 days ago
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
2 days ago
add a comment |
up vote
7
down vote
up vote
7
down vote
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 yesterday
answered 2 days ago
Andrzej Gis
6,48985196
6,48985196
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
2 days ago
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
2 days ago
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
2 days ago
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
2 days ago
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
2 days ago
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
2 days ago
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
2 days ago
@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
2 days ago
add a comment |
up vote
6
down vote
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 |
up vote
6
down vote
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 |
up vote
6
down vote
up vote
6
down vote
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 2 days ago
Mayer Spitzer
541313
541313
add a comment |
add a comment |
up vote
0
down vote
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 |
up vote
0
down vote
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 |
up vote
0
down vote
up vote
0
down vote
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 yesterday
answered yesterday
Caius Jard
7,73311135
7,73311135
add a comment |
add a comment |
up vote
0
down vote
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 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.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
New contributor
add a comment |
up vote
0
down vote
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 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.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
New contributor
add a comment |
up vote
0
down vote
up vote
0
down vote
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 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.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
New contributor
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 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.
Normal instantiation:
class logic -> template -> instance
Inheritance:
parent class logic + child class logic -> template -> instance
New contributor
New contributor
answered 17 hours ago
Jamiel Thomas
1
1
New contributor
New contributor
add a comment |
add a comment |
up vote
-1
down vote
No it will only create an instace of the child class.
New contributor
add a comment |
up vote
-1
down vote
No it will only create an instace of the child class.
New contributor
add a comment |
up vote
-1
down vote
up vote
-1
down vote
No it will only create an instace of the child class.
New contributor
No it will only create an instace of the child class.
New contributor
New contributor
answered 2 days ago
Sr.Mento
11
11
New contributor
New contributor
add a comment |
add a comment |
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