Dark Horse programmer —————— > Local inner class & anonymous inner class

Source: Internet
Author: User

-------Android Training, Java training, look forward to communicating with you! ----------

If an inner class is defined in a method, the inner class is a local inner class, and the local inner class is only valid in that method. Because local inner classes cannot be used outside the methods of external classes, local inner classes cannot be decorated with access control and the static modifier.

For local members, whether local or local, their upper-level program units are methods, not classes, and using static to decorate them has no meaning. Therefore, all local members cannot use the static modifier. Not only that, because the scope of a local member is where the method is, other program units never have access to local members in another method, so all local members cannot use the access control modifier.

If you need to define a variable with a local north, create an instance or derive a subclass, you can only do so within the same method as the local inner class.

1  Public classLocalinnerclass2 {3 4      Public Static voidMain (string[] args)5     {6         //defining local inner classes7         classInnerbase8         {9             intA;Ten         } One         //define subclasses of local inner classes A         classInnersubextendsInnerbase -         { -             intb; the         } -         //to create an object of a local inner class -Innersub is =Newinnersub (); -IS.A = 5; +is.b = 8; -System.out.println ("The A and B instance variables of the Innersub object are:" + IS.A + "," +is.b); +  A     } at  -}

JAVA8 improved anonymous inner class

Anonymous inner classes are suitable for creating classes that need to be used one at a time, and the syntax of an anonymous inner class is a little strange, as an instance of the class is created immediately when an anonymous inner class is created, and the class definition disappears immediately, and anonymous inner classes cannot be reused.

The format for defining an anonymous inner class is as follows:

New Implementation Interface () | Parent class Constructor (argument list) {      // Anonymous inner class class body part   }

As you can see, an anonymous inner class must inherit a parent class, or implement an interface but inherit only one parent class, or implement an interface.

There are two rules for anonymous inner classes:

1: Anonymous The inner class cannot be an abstract class, because an anonymous inner class object is created immediately when the system creates an anonymous inner class. Anonymous inner classes are therefore not allowed to be defined as abstract classes.

2: Anonymous inner class cannot define a constructor. Because the anonymous inner class does not have a class name, the constructor cannot be defined, but an anonymous inner class can define an initialization block that can be completed by the instance initialization block.

The most common way to create an anonymous inner class is to create an object of an interface type, as shown in the following program:

1 InterfaceProduct2 {3      Public DoubleGetPrice ();4      PublicString getName ();5 }6  Public classanonymoustest7 {8      Public voidTest (Product p)9     {TenSystem.out.println ("purchased a" + p.getname () + ", spent out" +P.getprice ()); One     } A      -      Public Static voidMain (string[] args) -     { theAnonymoustest TA =Newanonymoustest (); -         //When you call Test (), you need to pass in a product parameter -         //An instance of an anonymous implementation class is passed here -Ta.test (NewProduct () +         { -              + @Override A              Public DoubleGetPrice () at             { -                 return567.8; -             } -              - @Override -              PublicString getName () in             { -                 return"AGP graphics card"; to             } +         }); -     } the}

The test () method requires a Product object as a parameter, but the product knowledge is an interface that cannot create objects directly, so consider creating a product interface implementation class object here---If the product interface implementation class needs to be reused, The implementation class should be defined as a standalone class, and if the product interface implementation class needs to be used only once, an anonymous inner class can be defined in the same way as in the above program.

Defining an anonymous inner class does not require the class keyword, but rather the object that generates the anonymous inner class directly when the anonymous inner class is defined.

Because an anonymous inner class cannot be an abstract class, an anonymous inner class must implement its abstract parent class or all the abstract methods contained in the interface.

For the code above to create the product implementation class object, you can split it into the following code.

1  Public classAnonymoustestImplementsProduct2 {3     4 @Override5      Public DoubleGetPrice ()6     {7         return567.8;8     }9 Ten @Override One      PublicString getName () A     { -         return"AGP graphics card"; -     } the      -      Public voidTest (Product p) -     { -System.out.println ("purchased a" + p.getname () + ", spent out" +P.getprice ()); +     } -      +      Public Static voidMain (string[] args) A     { atAnonymoustest TA =Newanonymoustest (); -         //When you call Test (), you need to pass in a product parameter -Ta.test (Newanonymoustest ()); -     }     -}

When an anonymous inner class is created by implementing an interface, the anonymous inner class cannot explicitly create the constructor, so the anonymous inner class has only one implicit parameterless constructor, so the extension number after the new interface name cannot pass in the parameter value.

But if an anonymous inner class is created by inheriting the parent class, the anonymous inner class will have a constructor similar to the parent class, where the similarity refers to having the same argument list.

1 Abstract classDevice2 {3     PrivateString name;4      Public Abstract DoubleGetPrice ();5      PublicDevice () {}6      PublicDevice (String name)7     {8          This. Name =name;9     }Ten      One      PublicString GetName () { A         returnname; -     } -      Public voidsetName (String name) { the          This. Name =name; -     } -      - } +  Public classAnonymousinner - { +      Public voidTest (Device D) A     { atSystem.out.println ("purchased a" + d.getname () + ", spent out" +D.getprice ()); -     } -      Public Static voidMain (string[] args) -     { -Anonymousinner ai =NewAnonymousinner (); - //invoking an argument constructor to create an object for the device anonymous implementation class inAi.test (NewDevice ("Rice cooker")  -         { to @Override +              Public DoubleGetPrice () -             { the                 return67.8; *             } $         });Panax Notoginseng          - //call the parameterless constructor to create an object for the device anonymous implementation class theDevice d =NewDevice () +         { A             //Initialize block the             { +System.out.println ("Initialization block for anonymous inner class"); -             } $             //implementing an abstract method $ @Override -              Public DoubleGetPrice () -             { the                 return56.2; -             }Wuyi @Override the              PublicString getName () -             { Wu                 returnKeyboard; -             } About         }; $ Ai.test (d); -     } -}

The above program creates an abstract parent device class, which contains two constructors: one with no parameters and one with parameters. When you create an anonymous object with device as the parent class, you can pass in the parameter, which represents the constructor that invokes the parent class with parameters, or you can not pass in the parameter, which represents the call to the parent class without a parameter constructor.

When creating an anonymous inner class, you must implement all the abstract methods in the interface or abstract parent class, or you can override the normal methods in the parent class if necessary.

Dark Horse programmer —————— > Local inner class & anonymous inner class

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.