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

后端 未结 14 1191
执念已碎
执念已碎 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:32

    The assignments you are performing are called downcasting and upcasting. Downcasting is what happens when you cast an object to a String. Upcasting is the opposite where you are casting a type to a more general type. Upcasting never fails. Downcasting is only valid up until the point where you are downcasting to a type more specific than what the object was instantiated as.

    class Named
    {
        public string FullName
    }
    
    class Person: Named
    {
        public bool IsAlive
    }
    
    class Parent: Person
    {   
       public Collection Children
    }
    
    class Child : Person 
    {  
       public Parent parent;
    }
    
    public static void Main()
    {
      Named personAsNamed = new Person(); //upcast
      Person person = personAsNamed ; //downcast
      Child person = personAsNamed ; //failed downcast because object was instantiated
      //as a Person, and child is more specialized than(is a derived type of) Person
      //The Person has no implementation or data required to support the additional Child
      //operations. 
    }
    

提交回复
热议问题