0

我正在尝试编写一个程序,该程序从用户输入的扫描仪中读取所有单词,将它们放入 ArrayList 调用方法中,并打印长度小于 5 的所有单词的列表。是的,我可以在一个程序中编写它,但分配的目的是使用接口和继承。我编写了一个程序,将用户输入循环到对象数组中。我写了一个接口(这不能改变),我实现了一个类,它扫描数组中的单词并根据单词是少于五个还是多于五个字母给出一个布尔值。我编写了一个从类中获取答案并创建一个新的对象 ArrayList 的方法。如果单词少于五个字母,则将其添加到数组中。我正在尝试将该方法调用到我的主要方法中,但我得到一个“过滤器是抽象的” “无法实例化”错误...但我的界面不是抽象的?我不知道如何解决它,它让我发疯......非常感谢任何帮助。谢谢!

public interface Filters
{
    boolean accept(Object x);
//this interface cannot be changed.
}

public class SWordFilter implements Filters
{
//This is my subclass for the interface
    public boolean accept(Object x)
    {
    String y =(String) x;
    boolean accept=false;

    if (y.length()< 5)
    accept=true;
    return accept;
    }
}



import java.util.ArrayList;
import java.util.Scanner;

public class MyHomework
{
 //this is my main and my method.  I cannot call the method.
    public static void main(String[] args)
    {

        ArrayList<Object> names=new ArrayList<Object>();
        Scanner in=new Scanner(System.in);

        int i=0;
        while(i<5)
        {
            System.out.println("Enter the words");
            names.add(in.next());
            i++;
        }
        Filters tran= new Filters(names);
        Object result=collectAll(names,tran);
    }


public static ArrayList<Object> collectAll (ArrayList<Object> list, Filters f)

{
    ArrayList<Object> result= new ArrayList<Object>();

    for (int x=0; x<5; x++)
    {
        if (f.accept(list.get(x)))
        {
            result.add(list.get(x));
        }
        else
        {
        System.out.print("the word is too long");
        }
        //SWordFilter julie= new SWordFilter();
        //System.out.print(julie.accept(names.get(j)));
    }
    return result;
}
}
4

2 回答 2

1

问题出在这一行

Filters tran= new Filters(names);

由于Filters是接口,接口抽象类不能实例化,只能声明(分配)为对象获取内存。

所有成员函数(方法)都是抽象的,但您可以将其分配给实现此接口的类之一的新对象:

Filters tran = new SWordFilter();

理解这样的接口:

你有一些类需要有一个基类,就像java.util.List两者的基类java.util.ArrayList一样java.util.LinkedList,你不能实例化List,但你可以将它分配给ArrayListLinkedList因为抽象是专门设计为不被实例化的,它们具有共同的行为一些课程。

于 2013-07-12T21:46:28.777 回答
0

您不能实例化接口(因为它是抽象的),而是实例化实现过滤器的方法!

于 2013-07-12T21:48:23.323 回答