#Passing an interface as a parameter
12 messages · Page 1 of 1 (latest)
Which classes implement StringChecker ?
i think listexamples Im not sure
you can also just pass lambda since StringChecker only defines one method
whats "lambda"
so I would do filter name = new filter()?
for example:
StringChecker filter = new ListExamples();
you can do that because ListExamples implements StringChecker
or you can initialise the StringChecker directly but you need to implement the method
So basically there are 3 ways to use this interface
1.
StringChecker filter = new StringChecker() {
@Override
public boolean checkString(String s) {
return s.length() <5;
}
};
Anonymous class. You basically implement the methods yourself for this instance of StringChecker
2.
StringChecker filter = new ListExamples();
You can use a class which already implements StringChecker this is known as Polymorphism. Here you cannot define a custom implementation of the checkString method but will use the one provided by the class
3. (The method you dont know yet)
StringChecker filter = (myString) -> myString.length() < 5;
Does exactly what method one does. You can use lambda in combination with a functional interface.
In your case my guess would be that method number 1 fits your needs. You haven't learned about lambda yet but since you want to specify your own filter method nr.1 seems perfect.