The understanding of wildcard characters

Source: Internet
Author: User

First write a few classes

public class Animal {
	private String name;

	Public Animal (String name) {
		this.name = name;
	}
	
	public void Eat () {
		System.out.println (getName () + "can eat.");
	}
	
	Public String GetName () {return
		name;
	}
}

public class Cat extends Animal {public
	cat (String name) {
		super (name);
	}

	public void Jump () {
		System.out.println (getName () + "can jump.");
	}

public class Bird extends Animal {public
	Bird (String name) {
		super (name);
	}

	public void Fly () {
		System.out.println (getName () + "can fly.");
	}

public class Magpie extends bird{public
	Magpie (String name) {
		super (name);
	}

	public void Sing () {
		System.out.println (getName () + 
				"can not only eat,but sing");
	}

public class Animaltrainer {public
	Void Act (list<animal> List) {for
		(Animal animal:list) {
			Animal.ea T ();}}}

Write a test class when you are ready to do so

public class Testanimal {public
	static void Main (string[] args) {
		Animaltrainer animaltrainer = new Animaltrainer ();
		Test 1
		list<animal> animallist = new arraylist<> ();
		Animallist.add (New Cat ("CAT1"));
		Animallist.add (New Bird ("Bird1"));
		
		Animaltrainer.act (animallist);	Can be compiled
		
		//test 2
		list<cat> catlist = new arraylist<> ();
		Catlist.add (New Cat ("Cat2"));
		Catlist.add (New Cat ("CAT3"));
		
		This is because although Cat is a subclass of Animal, list<animal> and list<cat> have nothing to do with it, so they cannot compile
		animaltrainer.act (catlist);		Failed to compile
	}
}

The compiler cannot pass TEST2 compilation, because although Animal is the parent of Cat from the preceding code, there is no relationship between list<animal> and list<cat>, which is parallel. So it can't be passed in as a parameter, and in Test1, the first is the new List<animal> object, which is a subclass of Animal with the cat class, so the cat object can be add into the object of the List<ainmal> collection, This is not a conflict.

In order to make animaltrainer this tool method more applicable, you can use wildcard characters to expand, the specific operations are as follows.

public class Animaltrainer {public
	Void Act (list<. Extends Animal>list) {for
		(Animal animal:list) {
			Animal.eat ();}}

Change the method in the Animaltrainer class as shown above to increase the wildcard character List&lt. Extends animal> represents a generic that can add any subclass of Animal and Animal. Note for loops, which are represented by animal, that all elements of the list, regardless of their previous type, are treated as animal types, because as long as they are compiled, they are animal subclasses, which also embody polymorphism

For the upper bounds of the wildcard character, there are several basic rules: (assuming that the given generic type is G, (as in list<e> list), two specific generic parameters x, y, and that Y is a subclass of X (such as Animal and Cat on))

g<? Extends y> is g<? Subtypes of extends x> (such as list<? Extends cat> is list<? Extends the animal> of the type). G<x> is g<? The subtypes of the extends x> (such as list<animal> are list<? The subtypes of extends animal>) g<?> and g<? Extends object> equivalent, such as list<?> and list<? Extends objext> equals. One more thing to be aware of, Extends y> such wildcards, you cannot add any elements to it, and you can only add null if you want to add

	list<? Extends animal> list = new arraylist<> ();
		List.add (New Animal ("Animal"));
		List.add (New Bird ("Bird"));
		List.add (New Cat ("Cat"));

The code shown above cannot be compiled because the compiler cannot determine <. Extends animal> really represents what kind of class, simply don't let go inside add any elements or can only add null For the upper bounds of the wildcard character, there are several basic rules: (assuming that the given generic type is G, (as in list<e> list), two specific generic parameters x, y, and that Y is a subclass of X (such as Animal and Cat on))
g<? Super x> is g<? Subtype of Super y> (e.g. list<? Super animal> is list<? Subtype of Super bird>). G<x> is g<? Subtype of Super x> (e.g. list<animal> is list<?) Subtype of Super Animal>)
Observe the following code
list<? Super Bird> List1 = new arraylist<> ();
		List1.add (New Bird ("Bird"));
		List1.add (New Magpie ("Magpie"));
		List1.add (New Animal ("Animal"));//This one cannot be compiled

The code above is a new ArrayList () class, and is matched with the. Super Bird> Wildcard, The Super bird> represents the generic constraint: The Bird class and its parent class, and the third add statement cannot be compiled because, in an attempt to add a animal object to it, the compiler does not know. The super bird> generic constraint represents a Bird class, or a animal class, object class, or other Bird class constraint that is not compiled for security reasons. can be A;? Super bird> changed to <? Super Animal> so the third statement can be compiled and passed.
So if traversing list<? Super Bird> List1 This object.
for (Object B:list1)

In general, Extends t> cannot add elements to it, because he prescribes the upper bounds of the generic as T and specifies the class as specified, so the partial considerations, such as if it is unrelated to T, must not be put in; t's parent class, which does not conform to the polymorphic subclass, can point to the parent class reference. The parent class object cannot point to a subclass reference. Then there is the subclass of T, because the compiler does not know what kind of subclass it is, and in order to avoid errors, it is not allowed. Another way of thinking, if we pass Reflection TechnologyPut different elements into their common parent class, when taken out, it is easy to occur classcastexception exception, which does not conform to the Java language Specification and then discussed. Super t> Theoretically, it can either add elements or take out elements. Add elements first as long as the subclasses of T and T can be added. As for taking out the element, because it is impossible to determine the type of the parent class (which can be t or the parent of T), all objects are pointed to by object.
We can use wildcard characters to protect the parameters of a method. Prevent error operations from polluting data sources
Article Reference url:http://www.linuxidc.com/linux/2013-10/90928p4.htm
? Super T
? Super T

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.