我正在尝试解决这个问题,但我真的不明白语法。考虑以下代码:
class Parent {
private String productCode1; // Format X9999
private String productCode2;
public Parent(String productCode1, String productCode2)
{
this.productCode1= productCode1;
this.productCode2= productCode2;
}
}
然后我有一个包含我要调用的方法的子类
public Child extends Parent{
private String[] serialNumbers;
public Child(String productCode1, String productCode2, String... args){
super(productCode1, productCode2,);
int i = 0;
for(String serialN: args){
serialNumbers = new String[10];
serialNumbers[i]= serialN;
i++;
}
public String[] getSerialNumbers(){ //This is the method i want to call
return this.serialNumbers;
}
}
这是库存类
public class Inventory{
public ArrayList<Parent> products;
public Inventory(){
products = new ArrayList<Parent>(); //Some hard coded items
products.add(new Parent("A0001", "abcdefg"));
products.add(new Parent("B0010", "abcdefg"));
products.add(new Parent("C0100", "abcdefg"));
products.add(new Child("D1000", "abcdefg", "firstSN", "secondSN", "thirdSN"));
}
public static ProductLine getProduct(ArrayList<Parent> products, String productCode){
for(int i = 0; i < products.size(); i++){
ProductLine product = products.get(i);
if(product.getProductCode().equals(productCode)){
return product;
}
}
return null;
}
现在在主类中,我需要检查对象是父对象还是子对象,因为我正在尝试获取序列号,如果我得到序列号,则表示是子对象,否则是父对象.
我试图使用子类中的 getserialNumbers() 的唯一问题
public Application{
String inputProductCode = keyboard.nextLine(); //Input product code from user
Inventory inventory = new Inventory();
ProductLine pFound = inventory.getProduct(inventory.products, inputProductCode); //check if is Child item
String[] serNumb = pFound.getSerialNumbers(); //Here is where i get Error cannot find symbol/method getSerialNumbers
if(serNumb[0] == null){
// code continue...
}
我试着像这样投:
String[] serNumb = ((ItemisedProductLine)pFound).getSerialNumbers();
它可以编译,但他(如预期的那样)在运行时向我抛出“无法将父级转换为子级”。
我希望我能很好地解释很长的问题......