'JAVA - Trying to understand the 'big picture' of interfaces [duplicate]

I'm a beginner Java learner and I've been trying to follow the Euler Project.

I found Nayuki's solutions to the problems and I'm having difficulty wrapping my head around the need/purpose of the interface here. English isn't my first language so I'm a bit confused on what exactly is meant with the commentary of the interface here:

// This forces every solution class to implement a common interface,
// which is helpful for unit testing like in the EulerTest implementation.
public interface EulerSolution {
    
    public String run();
    
}

From what I've understood, it means that instead of running every problem class one by one, I can run the interface instead and run all the classes at the same time? So I don't necessarily need this interface to solve the problems, it's just a practical way to check that they're all working how they're supposed to.

I know programming is extremely abstract but I've been struggling with this for a couple of weeks. Maybe if I can finally grasp what exactly the interface is doing behind the scenes here I'll be able to understand interfaces, their function, and how they 'fit' into an overall program and its classes more easily.

Thank you lots for any help!



Solution 1:[1]

It's not about running all of the classes at the same time, but about insuring you can run all of the classes in the same way. By making every solution class implement this interface, it insures that they all of a run() method that returns a String.

Solution 2:[2]

Interfaces tell you what something can do. Any class that implements an interface defines the way that task is done. Every EulerSolution can run(). Your implementation of EulerSolution will work in the way you define, independent from other implementations. You might write:

public class SolutionA implements EulerSolution
{
    public String run()
    {
        return "Hello!";
    }
}

Another implementation could be:

public class SolutionB implements EulerSolution
{
    public String run()
    {
        return "Goodbye!";
    }
}

Why is this helpful? It allows you to do something like this:

public class ShowSolutions
{
    public static void main(String args[])
    {
        EulerSolution foo = new SolutionA();
        EulerSolution bar = new SolutionB();

        System.out.println(foo.run());
        System out.println(bar.run());

        //displays:
        //  Hello!
        //  Goodbye!
    }
}

If you wanted to test a new implementation, all you need to do is change SolutionA or SolutionB to the name of your class in the code above. If you have access to EulerTest, look at it and see if it does something similar in order to use your solutions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bill the Lizard
Solution 2 Nayuki