public class Boxcar<S extends Things> {
public ArrayList<S> contents = new ArrayList<S>(); //an arraylist of things
public static void main(String [] args){
Boxcar test = new Boxcar();
test.addContents(new Person("239-235-2535", "Ronald", 36)); //works 100%
}
public Boxcar(Things type, int maxElements){
this.type = type;
boxcarId = boxcarIdCount;
boxcarIdCount++;
this.maxElements = maxElements;
}
public void addContents(S thing) {
contents.add(thing);
}
...
}//end boxcar class
public class Person implements Things {
int age;
String govtId, name;
public Person(String govtId, String name, int age){
this.govtId = govtId;
this.name = name;
this.age = age;
}//end Consrtructor
public void load(ArrayList<Boxcar<?>> train){
Person dude = new Person("239-235-235", "Ronald", 36);
train.get(i).addContents(dude); // won't compile
}
...
}//end Person class
public interface Things {
public void load(ArrayList<Boxcar<?>> train, String [] params);
}//end interface Things
public class Train {
ArrayList<Boxcar<?>> train = new ArrayList<Boxcar<?>>();
public void load(Things thing, String [] params){
thing.load(train, params);
}
...
}
在上面的代码中,方法 addContents 在 Boxcar 类中执行时似乎工作正常。但是,当从 Person 类以完全相同的方式调用时,它的行为会有所不同。
这是什么原因,我该如何解决?