Introduction:

After learning anonymous inner class to understand the love letter.

/ / love letter
// In my world you are always 18
me.world(new You() {  // In my world there was only the original you
            public void getAge(a) {  // Your age
                System.out.println("18");  // Always 18}});Copy the code

The main content

  • Interface relationships with abstract and anonymous inner classes

The specific content

An anonymous inner class is an inner class that has no name. Because it has no name, it can only be used once. It is usually used to simplify code, but there is another prerequisite for using an anonymous inner class: you must inherit from a parent class or implement an interface. Why anonymous inner classes need to exist.

** Example: ** Observe the following code

interface Message {
    public void print(a);
}

class MessageImpl imlements Message {
    public void print(a) {
        System.out.println("Hello World !"); }}public class TestDemo {
    public static void main(String args[]) {
         fun(new MessageImpl());
    }
    
    public static void fun(Message msg) { msg.print(); }}Copy the code

Output result:

Hello World !
Copy the code

The normal rule is that an interface or abstract class needs subclasses that override all abstract methods. But if the MessageImpl subclass is now used only once, is it necessary to define it as a separate class? So at this point, you can simplify your code by using anonymous inner classes.

** Example: ** Simplified code

interface Message {
    public void print(a);
}

public class TestDemo {
    public static void main(String args[]) {
        fun(new Message() {
            public void print(a) {
                System.out.println("Hello World !"); }}); }public static void fun(Message msg) { msg.print(); }}Copy the code

Output result:

Hello World !
Copy the code

The following code block is called an anonymous inner class.

{
    public void print(a) {
        System.out.println("Hello World !"); }}Copy the code

When using anonymous inner classes, there is one prerequisite: they must be based on the application of an interface or abstract class. It is important to emphasize, however, that if an anonymous inner class is defined ina method, then the final keyword must be used if the parameters or variables of the method are to be accessed by the anonymous inner class (this requirement has been changed since JDK 1.8).

conclusion

Anonymous inner classes are developed on the basis of abstract classes and interfaces. The biggest benefit of anonymous inner classes is that they help users reduce class definition.