user34567
user34567

Reputation: 258

Java Interface Method call

I have a Java interface as below

public interface IFilter 
{
    public void doFilter();           
}

I have an implementation of this interface as Filter1, Filter2, .... I am adding these implementations to a List<IFilter>.

 private final List<IFilter> filterChain = new ArrayList<>();

Following is the sample impl class

public class FirstFilter implements IFilter
{
    private String name = "first";

    @Override
    public void doFilter()
    {
        System.out.println("First Filter !");
    }

    @Override
    public boolean equals(Object obj)
    {
        return super.equals(obj); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int hashCode()
    {
        return super.hashCode(); //To change body of generated methods, choose Tools | Templates.
    }

}

And I am iterating over this list to call doFilter().

public void filter()
{
     for(IFilter filter: filterChain)
     {
         filter.doFilter();
     }
}

But this gives an error

cannot find symbol filter.doFilter();
symbol: method doFilter()
location: variable filter of type IFilter where IFilter is a type-variable: IFilter extends Object declared in class FilterChain 1 error

I am not able to understand whats going wrong here?

Upvotes: 2

Views: 177

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

Note

where IFilter is a type-variable

I.e. you have something like

class FilterChain<IFilter> {
    ...
    public void filter() 
    {
         for(IFilter filter: filterChain)
         {
             filter.doFilter();
         }
    }
}

Here IFilter doesn't refer to the interface IFilter, but to the type parameter; it's exactly equivalent to

class FilterChain<T> {
    ...
    public void filter() 
    {
         for(T filter: filterChain)
         {
             filter.doFilter();
         }
    }
}

Upvotes: 4

Related Questions