For example, if I have an interface:
interface Executable {
void execute();
}
You wouldn't be able to explicitly instantiate it. If you tried to create a new instance of the interface Executable, you'd get an compile error, saying 'cannot instantiate the type Executable'.
However, when trying to pass an interface to a method, I realized that you could do this:
class Runner {
public void run(Executable e) {
System.out.println("Executing block of code...");
e.execute();
}
}
public class App {
public static void main(String[] args) {
Runner r = new Runner();
// When passing the Executable type, am I instantiating it?
r.run(new Executable() {
public void execute() {
System.out.println("Executed!");
}
});
}
}
How is this possible? Aren't you creating a new instance of interface Executable
because of the new
keyword? Is there something that I don't understand? A brief explanation and some examples are greatly appreciated!