Java-8.6 anonymous internal class

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.