I'm baffled by some source code I'm looking at, and I'm trying to get a better understanding. The code is below, but it is also available at Ideone where you can play with it yourself.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public interface Fruit {
public void apple();
}
Fruit interfaceFruit;
public void apple(){
System.out.println("apple");
if (interfaceFruit != null) {
interfaceFruit.apple();
}
}
public void setFruit(Fruit f) {
interfaceFruit = f;
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone test = new Ideone(){
@Override
public void apple() {
System.out.println("local override of apple");
}
};
System.out.println("1) ---");
test.apple();
Ideone test2 = new Ideone();
System.out.println("2) ---");
test2.apple();
test2.setFruit(new Fruit() {
@Override
public void apple() {
System.out.println("interface override of apple");
}
});
System.out.println("3) ---");
test2.apple();
}
}
The output is:
1) ---
local override of apple
2) ---
apple
3) ---
apple
interface override of apple
What exactly is going on in this code? There is an interface declared inside of a class (so, an inner interface, right?) and then the interface is declared as an instance variable to the class. This is where I'm confused.
I think what is happening is that if an anonymous inner class is instantiated for the interface Fruit
, we are creating an unnamed class that implements the interface. What I'm not totally getting is how or why the interface is stored in an instance variable to the class. What is the purpose of this? What is this practice called? This seems very strange and I'm not really sure what someone would get out of this.