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 inside the class. You cannot make changes to sub-segments of an outer class unless you use an initialization block

This is not going to work. ! The staring part is wrong.

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, and the compiler will make an error because the changes and actions at this time have no chance of running.

The actions and changes to the fields in the initialization block are possible.

This is not going to work.

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


Java anonymous inner class usage considerations

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.