在java中我有一个问题要问你。
我有产品类(class)和电视类(class)。 TV 类继承自 Product。我还有 Store 类。
Product类有变量和它自己的findMatch方法, TV 类有自己的变量和自己的 findMatch 方法, Store 类有 ArrayList 和 findProduct 方法
在驱动程序类中,我添加了一些产品,创建对象并将它们添加到 ArrayList 中。如果属性在 TV 类中,则尝试 findMatch 方法,它会找到。但我想查找的属性位于 Product 类(例如品牌)中,但找不到它。 这些代码有什么问题,我无法解决。
public class Product
{
private String barcode;
private String brand;
private String manufactureYear;
private int price;
private int yearOfGuarantee;
private int displaySize;
//constructor and set & get methods here
public boolean findMatch(String keyword)
{
return getBarcode().equals(keyword) ||
getBrand().equals(keyword) ||
getManufactureYear().equals(keyword)
|| Integer.toString(getPrice()).equals(keyword)
|| Integer.toString(getYearOfGuarantee()).equals(keyword)
||Integer.toString(getDisplaySize()).equals(keyword);
}
}
public class TV extends Product
{
private String type;
private String resolution;
//constructor and set&get methods here
public boolean findMatch(String keyword)
{
super.findMatch(keyword);
return getType().equals(keyword) || getResolution().equals(keyword);
}
}
public class Store
{
ArrayList<Product>pList=new ArrayList<>();
public void findProduct(String keyword)
{
for(int i=0; i<pList.size(); i++)
{
if(pList.get(i).findMatch(keyword)==true)
{
System.out.println(pList.get(i));
}
}
}
}
最佳答案
在您的 TV
findMatch
方法中,您调用该方法的父版本,但对返回的值不执行任何操作:
public boolean findMatch(String keyword)
{
super.findMatch(keyword);
return getType().equals(keyword) || getResolution().equals(keyword);
}
你可能想要这样的东西:
public boolean findMatch(String keyword)
{
return super.findMatch(keyword) || getType().equals(keyword) || getResolution().equals(keyword);
}
关于java - 无法从继承中找到匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858630/