我试图理解并完成尝试创建一个扩展接受所有类的类的泛型类的类的任务。到目前为止,我有这个工作。我正在尝试创建一个扩展通用holder类的类,并让该类只接受特定的对象。
示例,一个名为“ComputerOrder”的类,它不接受Apple或Orange对象,只接受ComputerPart或Peripheral对象,例如Motherboard或Printer对象。被困在这2周了。我不能为我的生活想出这个概念。任何帮助将不胜感激。
abstract class Product{
protected float price;
abstract float price();
public String toString() {
return "Price = " + String.valueOf(price) + " ";
}
}
class Apple extends Product{}
class Orange extends Product{}
class ComputerPart extends Product{
public ComputerPart(float p){
price = p;
}
public float price() {
return price;
}
}
class Motherboard extends ComputerPart{
protected String manufacturer;
public Motherboard(String mfg, float p) {
super(p);
manufacturer = mfg;
}
public String getManufacturer() {
return manufacturer;
}
}
class Peripheral extends Product{
public Peripheral(float p) {
price = p;
}
public float price() {
return price;
}
}
class Printer extends Peripheral{
protected String model;
public Printer(String model, float p) {
super(p);
this.model = model;
}
public String getModel() {
return model;
}
}
class Cheese extends Product{
public Cheese(float p) {
price = p;
}
public float price() {
return price;
}
}
class Cheddar extends Cheese{
public Cheddar(float p) {
super(p);
}
}
class GenericOrder<T>{
public ArrayList<T> storage = new ArrayList<T>();
private static int counter = 1;
public final int id;
public T obj;
public GenericOrder(){
id = counter;
counter++;
}
public void add(T item){
storage.add(item);
}
public T get(int in){
return obj;
}
public void getId(){
System.out.println(this.id);
}
public String toString(){
String ret = "";
Iterator<T> it = storage.iterator();
while (it.hasNext()) {
ret += it.next() + "\n";
}
return ret;
}
}
class ComputerOrder extends GenericOrder {
public void add(ComputerPart in){
if(in instanceof ComputerPart){
storage.add(in);
}
}
}
public class Tme2{
public static void main(String[] args){
ComputerOrder com = new ComputerOrder();
com.add(new Motherboard("bla", 3.33f))
}
}
答案 0 :(得分:5)
你可以这样做:
class ComputerOrder<T extends ComputerProduct> extends GenericOrder<T> {
//...
}
此处,ComputerProduct
是一个扩展Product
的类,您的所有计算机产品(如ComputerPart
或Peripheral
都会延伸ComputerProduct
。同样,您可以创建一个派生自FoodProduct
的{{1}}类,从Product
,Apple
和Orange
派生出来:
Cheese
声明class FoodOrder<T extends FoodProduct> extends GenericOrder<T> {
//...
}
是类型限制,可确保所有类型的<T extends ComputerProduct>
都来自T
,否则您将收到编译错误。
ComputerPart
类仍然是通用的,因此您可以为所有计算机产品实例订购:
ComputerOrder
但您也可以将其限制为外围设备:
ComputerOrder order = new ComputerOrder<ComputerProduct>();
// Add peripherals, printers, motherboards...
// Apples, ... will throw compiler errors...