?? We all know that in Java you can use an inner class to place the definition of a class inside the definition of another class, which is an inner class, but the anonymous inner class often makes us feel that it doesn't have a specific name, so how do we use it?
define an anonymous inner class
public interface Contents{ int value();}public class Test1{ private Contents contents() { return new Contents() { private int i = 11; @Override public int value() { return i; } }; } public static void main(String[] args) { Test1 test = new Test1(); Contents con = test.contents(); System.out.println(con.value()); }}
?? As above, we define an anonymous inner class that implements the contents interface, and the reference returned by the new expression is automatically converted to a reference to the contents, and the output is 11. This is the most basic anonymous inner class, just output a result, let's look at the anonymous inner class that uses an external object.
using anonymous inner classes with parameters
public interface Destination{ String readLabel();}public class Test2{ private Destination destination(final String dest) { return new Destination() { private String label = dest; @Override public String readLabel() { return label; } }; } public static void main(String[] args) { Test2 test2 = new Test2(); Destination d = test2.destination("Wu Han"); System.out.println(d.readLabel()); }}
?? The above anonymous inner class passed in a parameter that uses an externally defined object, and the compiler requires that its parameter reference be final. But in JDK1.8, there is no error even if it is not set to final.
initialization of anonymous inner classes
public interface Destination{ String readLabel();}public class Test3{ public Destination destination(final String dest, final float price) { return new Destination() { private int cost; { cost = Math.round(price); if(cost > 100) { System.out.println("超出预支"); } } private String label = dest; @Override public String readLabel() { return label; } }; } public static void main(String[] args) { Test3 test3 = new Test3(); Destination d3 = test3.destination("Wu Han", 101.1F); System.out.println(d3.readLabel()); }}
?? As above, the cost is initialized in the anonymous inner class, because the anonymous inner class does not have a name, so the initialization method naturally does not have a name.
?? After using the anonymous inner class, we use the factory method, which can become very simple and convenient.
?? In the end, one of the reasons why we need internal classes is that each inner class can inherit an implementation of (interface) independently, so no matter whether the perimeter class has inherited an implementation of (an interface), there is no effect on the inner class. As we can see from the above, anonymous inner classes implement interfaces directly with anonymous internal classes, which gives us convenience under certain conditions.
Anonymous inner class of Java inner class