Java泛型实例

Java泛型实例:

 

<textarea cols="50" rows="15" name="code" class="c-sharp">/** * */ package com; /** * @author Administrator * */ public class AnimalDoctor { /** * @param args */ public static void main(String[] args) { // test it Dog[] dogs = {new Dog(), new Dog()}; Cat[] cats = {new Cat(), new Cat(), new Cat()}; Bird[] birds = {new Bird()}; AnimalDoctor doc = new AnimalDoctor(); doc.checkAnimals(dogs); // pass the Dog[] doc.checkAnimals(cats); // pass the Cat[] doc.checkAnimals(birds); // pass the Bird[] } public void checkAnimal(Animal a) { a.checkup(); // does not matter which animal subtype each // Animal's overridden checkup() method runs } public void checkAnimals(Animal[] animals) { for (Animal a : animals) { a.checkup(); } } } abstract class Animal { public abstract void checkup(); } class Dog extends Animal { public void checkup() { // implement Dog-specific code System.out.println("Dog checkup"); } } class Cat extends Animal { public void checkup() { // implement Cat-specific code System.out.println("Cat checkup"); } } class Bird extends Animal { public void checkup() { // implement Bird-specific code System.out.println("Bird checkup"); } } </textarea>

 

Dog checkup
Dog checkup
Cat checkup
Cat checkup
Cat checkup
Bird checkup

 

 

<textarea cols="50" rows="15" name="code" class="c-sharp">/** * */ package com; import java.util.ArrayList; import java.util.List; /** * @author Administrator * */ public class AnimalDoctorGeneric { // change the argument from Animal[] to ArrayList&lt;Animal&gt; public void checkAnimals(List&lt;? extends Animal&gt; animal) { for (Animal a : animal) { a.checkup(); } } public static void main(String[] args) { // make ArrayLists instead of arrays for Dog, Cat, Bird List&lt;Dog&gt; dogs = new ArrayList&lt;Dog&gt;(); dogs.add(new Dog()); dogs.add(new Dog()); ArrayList&lt;Cat&gt; cats = new ArrayList&lt;Cat&gt;(); cats.add(new Cat()); cats.add(new Cat()); List&lt;Bird&gt; birds = new ArrayList&lt;Bird&gt;(); birds.add(new Bird()); // this code is the same as the Array version AnimalDoctorGeneric doc = new AnimalDoctorGeneric(); // this worked when we used arrays instead of ArrayLists doc.checkAnimals(dogs); // send a List&lt;Dog&gt; doc.checkAnimals(cats); // send a List&lt;Cat&gt; doc.checkAnimals(birds); // send a List&lt;Bird&gt; } } </textarea>

 

Dog checkup
Dog checkup
Cat checkup
Cat checkup
Bird checkup

 

 

List<? extends Animal> aList = new ArrayList<Dog>();

在上文件中可以使用

 

 

你可能感兴趣的:(java,String,Arrays,Class)