Anonymous inner class using an interface in Java

后端 未结 1 1863
不思量自难忘°
不思量自难忘° 2020-12-20 07:48

So, when looking into lambda expressions and using them to substitute anonymous inner classes for EventHandlers in Java, I came across a few anonymous inner classes that mad

相关标签:
1条回答
  • 2020-12-20 08:12

    1) Why are we able to create an anonymous inner class directly from an interface rather than having to create one through a class that implements the interface?

    2) Why am I unable to create an anonymous inner class that implements ActionListener instead of directly from it as I show in my second code snippet?

    When you create a class using implements XXXX, you are defining a class(inner or non-inner), and you will have to give it a name, sure we can do that and this is what we often do . While anonymous inner class dose not have a name, and it is more like an expression.


    I copy this from http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

    And I think this will help you to understand what anonymous class is.

    An anonymous class is an expression. They are like local classes except that they do not have a name

    . 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.

    Consider the instantiation of the frenchGreeting object:

        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);
            }
        };
    

    The anonymous class expression consists of the following:

    • The new operator

    • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

    • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

    • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

    Because an anonymous class definition is an expression, it must be part of a statement. In this example, the anonymous class expression is part of the statement that instantiates the frenchGreeting object. (This explains why there is a semicolon after the closing brace.)

    0 讨论(0)
提交回复
热议问题