In this case, Most of the people says, “Parent's can hold to children but children cannot”
Let’s see the below example,
class Parent
{
public void display1()
{
Console.WriteLine("Parent");
}
}
class Child : Parent//Class Child extends Parent(in case of Java Lang.)
{
public void display()
{
Console.WriteLine("Child");
}
}
class Program
{
static void Main(string[] args)
{
Child aChild = new Child();
Parent aParent = new Parent();
aParent = aChild;// its valid.
aChild = aParent;// its not valid. Why?
}
}
Reason:
- Inheritance is "type of" not "contains". So the Child is Type Of Parent, But the Parent is not a type of Child. In this way the above example working.
- Technically, Object is a logical reference (heap memory) of physical things (Signatures/Codes – stored into Stack memory). In Child class having the heap reference of Parent class so that we can assign. But the Parent class object does not have the Child reference so we can’t.
- Reason of this situation: This is basically used, the child already created one object. But we know the use is exactly Parent class. So just we assign the reference, no need to create a reference and assign
- Example:
int I ;
int J ;
I = 2 * 3 / 6;
J = I ;
07:44 |
Category:
C# Concepts
|
0
comments
Comments (0)