0

The below example I had seen in oracle doc for anonymous classes example.But how they can write interface HelloWorld inside a class HelloWorldAnonymousClasses

public class HelloWorldAnonymousClasses {

      interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }

    public void sayHello() {

        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }

        HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}
shree18
  • 1,279
  • 1
  • 11
  • 15
  • Why do you think that should be an issue? The interface is just a member of the class. It has nothing to do with anonymous classes? – Rohit Jain Nov 25 '13 at 13:11
  • @RohitJain: he's probably refering to this line `HelloWorld frenchGreeting = new HelloWorld()` – Jeroen Vannevel Nov 25 '13 at 13:12
  • @JeroenVannevel I don't think he meant that. I re-read the question, and I didn't find it leading to that question. It is clearly asking - *how they can write interface `HelloWorld` **inside** a class `HelloWorldAnonymousClasses`* – Rohit Jain Nov 25 '13 at 13:15
  • @RohitJain: Hmm, I tend to agree with you. I'll clarify it in my response either way (I thought the anonymous interface implementation would cause confusion here, not that). – Jeroen Vannevel Nov 25 '13 at 13:16

4 Answers4

3

Interfaces can be anonymously implemented. This will not be an implementation of the interface, but rather the implementation of an interface in an anonymous subclass.

The interface itself doesn't get instantiated.

The line in question is this:

HelloWorld frenchGreeting = new HelloWorld() {

where HelloWorld is an interface. The curly brackets already indicate that this is an anonymous class. By defining it as HelloWorld you force the anonymous class to implement the methods defined in the interface.

If you are referring to the interface itself being defined inside class: if you want to have an interface defined for only the current class without exposing it to other objects, you can define it inside your class.

If you want to make it available to the outside world as well, you'll have to declare your class and interface public and access it using MyClass.MyInterface.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • Is it a feature of Java8? – shree18 Nov 25 '13 at 13:10
  • To explain it a bit further, anyone wanting to implement HelloWorld will do it this way: public class ExampleHelloWorld implements HelloWorldAnonymousClasses.HelloWorld { //methods and properties here } – Goran Štuc Nov 25 '13 at 13:10
  • @GoranŠtuc: no, that is not what he means. I'll clarify it in my response. – Jeroen Vannevel Nov 25 '13 at 13:13
  • @JeroenVannevel: actually in this case that is not true, since any interface declared is public anyone outside can use this interface, in this case the only solution could be to refactor the main class to package visibility to prevent other classes outside of this package to use it – Goran Štuc Nov 25 '13 at 13:17
  • @Batty It will compile even in Java 5. – Rohit Jain Nov 25 '13 at 13:18
  • I was not sure about version support, just wanted to say, this is not something new from Java 8 :) – codingenious Nov 25 '13 at 13:20
1

You can declare nested interfaces in the same way as you can declare static nested classes and inner classes. A nested interface declaration is implicitly static (Java Language Specification §8.5.1) - an "inner interface" wouldn't make sense because every instance of an inner class holds a reference to the relevant instance of the containing class, and you can't create an instance of an interface (only of a class that implements the interface).

In your example the interface definition has default visibility (it isn't declared public, protected or private) so any class that is in the same package as HelloWorldAnonymousClasses could refer to the nested interface as HelloWorldAnonymousClasses.HelloWorld.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

There may be a scenario, where you need multiple implementations of a interface inside a class(and only to that class, you don't want to expose), so Java provides feature of declaring Interface inside class.

You can refer here, similar question.

Community
  • 1
  • 1
codingenious
  • 8,385
  • 12
  • 60
  • 90
0

If you read the tutorial trail a little farther, it actually can answer your question.

An anonymous class definition is an expression, it must be part of a statement. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.

The instantiation of the frenchGreeting object in your example:

HelloWorld frenchGreeting = new HelloWorld() { /* other code */ };

The anonymous class expression is part of the statement that instantiates the frenchGreeting object, ended by a semicolon after the closing brace. the anonymous class is implementing the interface HelloWorld. When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

Sage
  • 15,290
  • 3
  • 33
  • 38