1
public interface InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }
    interface Presentable extends Gift, Guest { }
    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
                @Override public void present() {
                    System.out.println("Heeeereee's Johnny!!!");
                }
            };
        johnny.present();                     
        ((Gift) johnny).present();            
        ((Guest) johnny).present();           
        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();              
        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();
    }
}

This code compiles and runs the main() function without error, what concept am I missing here?

nayan
  • 21
  • 3

1 Answers1

1

johnny is an instance of an anonymous subclass. From the link:

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

The reason your code compiles is because the implementation of present is provided in this anonymous subclass. To drive the point further, this:

Presentable johnny = new Presentable();

would not compile. However, this:

Presentable johnny = new Presentable() {
    @Override public void present() {
         // Do something
    }
};

is perfectly valid.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52