Image explanation of super and extends in generics

Source: Internet
Author: User
  1. // Apple orange inherits from the fruit class and Jonathan is a subclass of apple.
  2. List <?ExtendsFruit> List =NewArraylist <Apple> ();
  3. // List. Add (new Apple (); Error
  4. // List. Add (new fruit (); Error
  5. List <?SuperFruit> List =NewArraylist <Apple> ();
  6. List. Add (NewApple (); // Yes
  7. List. Add (NewFruit (); // Yes
  8. List <?ExtendsFruit> List =NewArraylist <Apple> ();
  9. Why can't fruit and fruit classes be added to the list?
  10. List <?ExtendsFruit> indicates that the upper limit is fruit. The following values are valid.
  11. List <?ExtendsFruit> list1 =NewArraylist <fruit> ();
  12. List <?ExtendsFruit> list2 =NewArraylist <Apple> ();
  13. List <?ExtendsFruit> list3 =NewArraylist <Jonathan> ();
  14. If list <?ExtendsFruit> If the add method is supported
  15. List1 can add fruit and all fruit subclasses.
  16. List2 can add apple and all apple subclasses.
  17. List3 can add Jonathan and all the child classes of Jonathan.
  18. In this case, the problem arises.
  19. List <?ExtendsFruit> the object to be held is a subclass of fruit.
  20. The subclass is still unknown, so adding any fruit subclass will be problematic, because if you add apple
  21. It is possible to list <?ExtendsThe object held by fruit> isNewArraylist <Jonathan> ()
  22. Apple cannot join. If you add Jonathan
  23. It is possible to list <?ExtendsThe object held by fruit> isNewArraylist <subclass of Jonathan> ()
  24. The addition of Jonathan is invalid, so list <?ExtendsFruit> list cannot be added
  25. And list <?SuperFruit> list indicates that the object held by the list is the parent class of fruit, and the lower limit is fruit. Therefore, it is no problem to add the fruit or fruit subclass to the list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.