#Passing an interface as a parameter

12 messages · Page 1 of 1 (latest)

analog lagoon
#

IDK how to pass an interface as a parameter and super confused.

storm pawn
#

Which classes implement StringChecker ?

analog lagoon
storm pawn
#

you can also just pass lambda since StringChecker only defines one method

analog lagoon
#

whats "lambda"

storm pawn
#

ok so please ignore that

#

you can pass an instance of listexamples

analog lagoon
#

so I would do filter name = new filter()?

storm pawn
#

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.