會不會報錯?在多少行?怎麼修改?java
import javax.swing.*; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List<Phone> phoneList = new ArrayList<>(); phoneList.add(new Phone()); phoneList.add(new Phone()); List<Water> waterList = new ArrayList<>(); waterList.add(new Water()); waterList.add(new Water()); SellGoods sellGoods=new SellGoods(); sellGoods.sellAll(phoneList); sellGoods.sellAll(waterList); } } abstract class Goods{ public abstract void sell(); } class Phone extends Goods{ @Override public void sell() { System.out.println("賣手機"); } } class Water extends Goods{ @Override public void sell() { System.out.println("賣水"); } } class SellGoods{ public void sellAll(List<Goods> goods){ for (Goods g:goods){ g.sell(); } } }
答案ide
//錯誤在1六、17行,翻譯後以下 List<Goods> goods=new ArrayList<Phone>();//這在集合中是不容許的,必須先後泛型保持一致 //修改:將38行改爲 public void sellAll(List< ? extends Goods> goods)//意思是goods和它子類均可以
不須要強制轉換this
避免了運行時異常翻譯
public class customizeGeneric<T> { private T name; public T getName() { return name; } public void setName(T name) { this.name = name; } public static void main(String[] args) { customizeGeneric<String> cg=new customizeGeneric<>(); cg.setName("han"); System.out.println( cg.getName()); } }
public class customizeGeneric<T,X> { private T name; private X age; public customizeGeneric(T name, X age) { this.name = name; this.age = age; } public T getName() { return name; } public void setName(T name) { this.name = name; } public X getAge() { return age; } public void setAge(X age) { this.age = age; } public static void main(String[] args) { customizeGeneric<String,Integer> cg=new customizeGeneric<>("han",21); System.out.println(cg.getName()+" "+cg.getAge()); } }
public class GenericMethod<T> { public void printValue(T t){ System.out.println(t); } public static void main(String[] args) { GenericMethod gm=new GenericMethod(); gm.printValue(16); } }
或者code
public class GenericMethod { public<T> void printValue(T t){ System.out.println(t); } public static void main(String[] args) { GenericMethod gm=new GenericMethod(); gm.printValue(16); } }