Java Important Technology (23) question mark wildcard for generics

Source: Internet
Author: User

1.1.A question mark wildcard character

There are three different ways to use the question mark wildcard in a type parameter:

(1) Generic<?> indicates that the type parameter is of any object type.

(2) generic<? Extends B> represents a derived class with a type parameter of b or b .

(3) generic<? Super B> represents a parent class with a type parameter of b or b .

Static classA {}Static classBextendsa{}Static classCextendsb{}Static classGeneric<t> { }    Static classholder{//Generic<?> can accept various parameterized types with different type parameters.       Public voidWork (generic<?>obj) {  }         //extends B indicates that a type parameter can be a derived class of B, or B.       Public voidWORKFORBC (generic<?extendsB>obj) {     }         //? Super B indicates that the type parameter can be either B or the parent of B.       Public voidWorkforab (generic<?SuperB>obj) {     }        }  Public Static voidMain (string[] args) {Holder Holder=NewHolder ();//Work (generic<a> obj);Holder.work (NewGeneric<a>()); //Work (generic<b> obj);Holder.work (NewGeneric<b>()); //Work (generic<c> obj);Holder.work (NewGeneric<c>()); HOLDER.WORKFORBC (NewGeneric<b>()); HOLDER.WORKFORBC (NewGeneric<c>());//error, A is the parent class of B. //HOLDER.WORKFORBC (New generic<a> ());Holder.workforab (NewGeneric<a>()); Holder.workforab (NewGeneric<b>());//error, C is a derived class of B. //Holder.workforab (New generic<c> ()); } } 

Java Important Technology (23) question mark wildcard for generics

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.