-2

The line List<Banana>list3=filter(list, new SmallBanana()); doesn't compile with a message:

No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).

I wanted to know how can i pass that instead of the interface itself if it's possible.

class Banana {
    int length;
    int width;
    Banana(int length, int width) {
        this.length=length;this.width=width;
    }
    public int getLenght() {return length;}
    public int getWidth(){return width;}
}

public class Test {

public static void main(String[] args){
    List<Banana>list = new ArrayList<>();
    List<Banana>list2=filter(list, (a)->a.length>15&&a.width>4);
    List<Banana>list3=filter(list, new SmallBanana());      
}

interface Filter{
    boolean test(Banana banana);
}

public static List<Banana> filter(List<Banana>list, Filter f){
    List<Banana>newBanana = new ArrayList<>();
    for(Banana y : list){
        if(f.test(y))
            newBanana.add(y);
    }
    return newBanana;
}

class SmallBanana implements Filter{
    public boolean test(Banana banana){
        return banana.length<15&&banana.width<4;
    }
}

}
default locale
  • 13,035
  • 13
  • 56
  • 62
T4l0n
  • 595
  • 1
  • 8
  • 25
  • `The line ... doesn't work` What do you mean? Tell us what exactly happens and why do you think it's wrong. – default locale Nov 18 '15 at 04:20
  • No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test). – T4l0n Nov 18 '15 at 04:21
  • 2
    aah, just declare `SmallBanana` outside of `Test`. Or check out this question: http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible – default locale Nov 18 '15 at 04:24
  • Here's a tip: if you have a cryptic compilation error, just paste message text in google. It helps most of the time. – default locale Nov 18 '15 at 04:33

1 Answers1

1

It doesn't work because SmallBanana is an inner class of Test and since it isn't a static inner class ,you main() can't access it directly ,you can either mark SmallBananaas static or use

Test t =new Test();
SmallBanana b = t.new SmallBanana();
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24