Java anonymous inner class usage considerations

Source: Internet
Author: User

1, first anonymous inner class to inherit from the abstract base class or implement the base class interface

Like this

Abstract class Seed{int Cnt;public Seed (int x) {cnt=x;} abstract void Showinfo ();} Class Apple{int Num=300;public seed getseed (final int x) {return new Seed (x) {public void Showinfo () {System.out.println (" The Apple's seeds is "+num);}};}

2. The parent class field cannot be initialized within the class unless the initialization block is used, and the child segments of the outer class cannot be changed

That's not going to work,//!. The comment section is not correct

Abstract class Seed{int Cnt;public Seed (int x) {cnt=x;} abstract void Showinfo ();} Class Apple{int Num=300;public seed getseed (final int x) {return new Seed (x) {//!num=200;//!cnt=100;public void Showinfo () {System.out.println ("The Apple ' s seeds is" +num);}};}
Reason:

The so-called anonymous inner class is essentially the same as the real name class, while the position of the inner segment of the class can only be declared or inside the constructor, and changes to the value of the field can only be made within the class method. Changes to field values in other locations are not valid because changes and actions at this time have no chance of execution, so the compiler will make an error. It is possible to manipulate and change the fields in the initialization block.

This is not going to work.

public class wrapping{public int a;public int b;//!a=100;}


Usage Considerations for anonymous internal classes of Java

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.