Why can't reference to child Class object refer to the parent Class object?

后端 未结 14 1122
执念已碎
执念已碎 2020-12-17 10:50

I was explaining OOP to my friend. I was unable to answer this question. (How shameful of me? :( )

I just escaped by saying, since OOP depicts the real world. In rea

14条回答
  •  执念已碎
    2020-12-17 11:18

    The Heap-Stack answer by AaronLS makes perfect technical sense.

    References are store on stack while objects are store on heap. We can assign child object to parent type reference because child is type of parent and child object has reference for parent class. While parent is not of type child. Parent object doesn’t have reference to child so child reference can’t point to parent object.

    This is the reason why we can cast decimal to int and int to decimal. But we can not cast parent-child both ways. Because parent has no clue about its children's references.

    Int i = 5;
    Decimal d = 5.5;
    
    d = i;
    
    or 
    
    i = d;
    

    Both are valid. But same is not the case with reference types which are stored on heap.

提交回复
热议问题