previous | index | next

Programming with Interfaces

Consider the following interface type:
public interface Filter
{
    boolean accept(Object x);
}
Classes that implement Filter supply criteria used to accept the object x. For example, a StringFilter class might accept strings that are three characters or less in length. If sf is a StringFilter object, then sf.accept("abc") returns true, while sf.accept("abcd") returns false.

Write the StringFilter class. Recall that the String class has a method of no arguments called length that returns the length of the implicit argument.

class StringFilter implements Filter
{
    public boolean accept(Object x)
    {
	String s = (String)x;
	if ( s.length() <= 3 )
	    return true;
	else
	    return false;
    }
}

previous | index | next