wildcard character, upper and lower limit of generic type

Source: Internet
Author: User

One: Wildcard characters

Because generics are initialized to determine the type of data, and the method that accepts this property of this object or object is fixed, it is necessary to judge and limit the types of these properties that pass through this method, otherwise, a method that can only come out of an integer type if passed in a string type, An error occurs during the execution of this method. If this method can handle any type of data, you can use the wildcard character ". "To receive.

Example 1:

Package haizhu.com;

Class student<t>{
	private T name;
	Public T GetName () {
		return name;
	}
	public void SetName (T name) {
		this.name = name;
	}
}

public class GenericDemo01 {public
	static void function (Student<?> s) {				//use ". "indicates that this method can receive a property of T corresponding to any data type
		System.out.println (" name is: "+s.getname ());
	}
	public static void Main (string[] args) {
		student<string> s = new student<string> ();
		S.setname ("Haizhu");
		function (s);
	}
}

II: Generic Upper and lower limits

However, in general, some methods can only handle a subset of data types, this time you can use the upper and lower limits to determine the range, the format is as follows:

Generic limit:

<? Extends Class >

Example 2:

	public static void function (STUDENT<? extends number> s) {
		System.out.println ("name is:" +s.getname ());
	}
Indicates that only the data type of the class of number and the subclass of this class can be received. (Extends table inheritance, that's what's underneath this class)

Generic Lower limit:

<? Super Class >
Example 3:

	public static void function (STUDENT<? super Number> s) {
		System.out.println ("name is:" +s.getname ());
	}
Indicates that only the class of number and the data type of the parent class of this class can be received. (Super Table parent class, more than this class of things)




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.