Java-8.6 anonymous internal class
In this section, we will discuss anonymous internal classes.
We have mentioned the internal class as follows:
package com.ray.ch03;public class Test {private class OneTest implements MyTest {@Overridepublic void test() {}}private MyTest myTest() {return new OneTest();}public static void main(String[] args) {new Test().myTest();}}interface MyTest {void test();}
The internal class above seems to be okay, but most of the time I only need it to help, it is basically not available in other places, so we can simplify it and change it to an anonymous internal class, it is only used for auxiliary methods.
Note: The implementation of anonymous internal classes requires the combination of interfaces or abstract classes.
Let's change the above Code to the following example:
package com.ray.ch03;public class Test {private MyTest myTest() {return new MyTest() {@Overridepublic void test() {}};}public static void main(String[] args) {new Test().myTest();}}interface MyTest {void test();}
I have summarized several notes:
1. You can only select one of the inheritance or implementation interfaces.
2. constructor cannot be defined
3. static cannot be used.
4. It cannot be abstract.
Package com. ray. ch03; public class Test {private MyTest myTest () {// It cannot inherit from MyTest2 and can only be returned when the return type is mytest2. Return new MyTest () {// public MyTest () {}// error // private static int id = 1; // error @ Overridepublic void test (){}};} public static void main (String [] args) {new Test (). myTest () ;}} interface MyTest {void test () ;} class MyTest2 {}
Summary: This chapter briefly describes anonymous internal classes.