Logic and its application to Collections.Generic and inheritance

后端 未结 6 1830
猫巷女王i
猫巷女王i 2021-01-06 20:49

Everything inherits from object. It\'s the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.

object me = new Person();
         


        
6条回答
  •  情话喂你
    2021-01-06 21:35

    At first glance, this does not make intuitive sense. But it does. Look at this code:

    List people = new List();
    List things = people; // this is not allowed
    // ...
    Mouse gerald = new Mouse();
    things.add(gerald);
    
    
    

    Now we suddenly have a List of Person objects... with a Mouse inside it!

    This explains why the assignment of an object of type A to a variable of type A is not allowed, even if S is a supertype of T.

    提交回复
    热议问题