【发布时间】:2020-03-18 20:37:18
【问题描述】:
我有产品对象和两个类 AsiaProductValidation 和 ProductValidation.AsiaProductValidation 在区域为亚洲时被调用。 ProductValidation 是父类,它有一些可以在 AsiaProductValidation 中使用的功能。我想知道我可以在 AsiaProductValidation 中编写 validate 方法来重用在父类中编写的一些检查
class Product{
int id,
long price;
String region;
Product(int id, long price, String region){
this.id = id;
this.price = price;
this.region = region;
}
// getters for id,price and locId
}
Class ProductValidation{
public static validate(List<Product> list, int qty, int totalAvailableQty){
if(list.size() == 0)
return //some expceptio
if(qty < totalAvailableQty){
return //some exception
}
if(qty == totalAvailableQty){
calculate(list);
}
}
private long[] calculate(List<Product> list){
return list.stream().mapTolong(p -> p.getPrice()).toArrat()l
}
}
class AsiaProductValidation{
public static validate(List<Product> list, int qty, int totalAvailableQty){
// First two conditions stay same as above
if(list.size() == 0)
return //some expceptio
if(qty < totalAvailableQty){
return //some exception
}
//only calculate function changes, how can i use inheritance here to avoid writing above two
checks in this class. and also call above two checks when this class is called?
calculate(list);
}
private long[] calculate(List<Product> list){
return list.stream().mapTolong(p -> p.getPrice() < 100 ? 0 : p.getPrice()).toArray();l
}
}
class RegionCalculate{
public void call(List<Product> list, int qty, int totalAvailableQty ){
if(region == Asia){
AsiaProductValidation.validate(qty,totalAvailableQty )
}
else{
ProductValidation.validate(qty,totalAvailableQty)
}
}
}
long[] price = {40, 90, 40};
List<Product> list = new ArrayList();
list.add(new Product(1,100, "ASIA"));
list.add(new Product(1,110, "AUS));
list.add(new Product(1,90, "EUROPE"));
RegionCalculate reg = new RegionCalculate();
reg.call(list, 1100, 500);
【问题讨论】:
-
你想要的是类扩展。标准做法是使用需要实现或您想要扩展的抽象方法创建一个抽象类。然后在您的子类中,您将首先调用超类方法(例如 super.validate())
-
return //some exception是什么意思?你的意思是throw?static和非static方法的混合不起作用。当你想要可覆盖的方法时,不要使用static。然后,当您从calculate中删除private修饰符时,您可以在子类中重写它,而无需重写calc方法。