您可以在代码中看到vehicle()类是一个超类。我想保留两个单独的课程(至少我认为这是最有效的方法。请指出我是否会采取相反的方式!),一个用于车辆,一个用于车辆用户,车主也列出车辆在vehicle()类中。基本上,我将使用他们独特的ownerId向搜索所有者提供控制台输入,并且还显示关于他们的车辆类型的各种信息字段(例如mpg,最高速度,基于购买日期的转售价值等)。我想使用有效的编码实践,并将每个对象项添加到列表看起来有点尴尬。有不同的出路吗?
下面是我的vehicleOwner课程
public class VehicleOwner extends Vehicle{
private int yearsOwned;
private String ownerName;
private int ownerId;
public VehicleOwner(String ownerBrand, String ownerModelNo,int ownerModelYear, int yearsOwned, String ownerName, int ownerId) {
super(ownerBrand, ownerModelNo, ownerModelYear);
this.yearsOwned = yearsOwned ;
this.ownerName = ownerName;
this.ownerId = ownerId;
ArrayList<VehicleOwner> list = new ArrayList<VehicleOwner>();
VehicleOwner owner1 = new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011);
VehicleOwner owner2 = new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012);
VehicleOwner owner3 = new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013);
list.add(owner1);
list.add(owner2);
list.add(owner3);
}
}
答案 0 :(得分:1)
唯一可以&#34;缩短&#34;此代码添加新对象而不为它们创建变量:
list.add(new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011));
list.add(new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012));
list.add(new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013));
答案 1 :(得分:0)
您可以使用Arrays.asList(T...)
并删除本地参考,然后请编程到List
界面。像
List<VehicleOwner> list = new ArrayList<>(Arrays.asList( //
new VehicleOwner("Volvo", "XC60", 2014, 3, "Mary", 00011), //
new VehicleOwner("Subaru", "crosstrek", 2015, 2, "John", 00012), //
new VehicleOwner("Mercedes", "Eseries", 2016, 1, "Brandon", 00013) //
));