java - 无法从继承中找到匹配项

标签 java inheritance

在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/

相关文章:

java - 用于绘制圆的 While 循环

java - 通用类型和 Instanceof

java - 我应该扩展 ArrayList (is-a) 还是应该将其作为成员包含 (has-a)?

inheritance - Kotlin: "val someVar = if (xx) 1 else 1.0",为什么 someVar 是 "Any"?

python - 我如何确保为层次结构中的每个类调用一个方法(一次,如果存在)?

jar 中的 java.lang.RuntimeException : Error scanning entry module-info. 类

java - 使用 JUnit 测试服务器

Java ArrayList - 错误

Java无法读取该字符是换行符

java - 我无法执行虚拟方法调用