The typical way to create an inner class is to create it inside a method body, and the local inner class cannot have an access specifier because it is not part of the perimeter class, but it can access constants within the current code block, as well as all members of this perimeter class. The following example compares the creation of a local inner class to an anonymous inner class.
Specific code implementation:
1 PackageThinking.in.java.demo;2 3 //define an interface4 InterfaceCounter {5 intnext ();6 }7 8 //Main class Localinnerclass9 Public classLocalinnerclass {Ten //defines a count of the tag counts; One Private intCount = 0; A - //using local inner classes -Counter Getcounter (FinalString name) { the classLocalcounterImplementsCounter { - PublicLocalcounter () { -System.out.println ("Localcount ()"); - } + - Public intNext () { +System.out.print (name+ ":"); A returncount++; at } - } - //the largest difference between a local inner class and an anonymous inner class: a local inner class can return an object of more than one inner class - //In stark contrast to the code in the anonymous inner class below - return Newlocalcounter (); - } in - //using anonymous inner classes toCounter GetCounter2 (FinalString name) { + return NewCounter () { - { theSystem.out.println ("Counter"); * } $ Panax Notoginseng @Override - Public intNext () { theSystem.out.print (name+ ":"); + returncount++; A } the }; + } - $ /** $ * @paramargs - */ - Public Static voidMain (string[] args) { theLocalinnerclass lic =NewLocalinnerclass (); - //local inner classWuyiCounter C1 = lic.getcounter ("Local inner"); the //Anonymous Inner class -Counter C2 = lic.getcounter2 ("Anonymous inner"); Wu for(inti = 0; I < 5; i++) { - System.out.println (C1.next ()); About } $ for(intj = 0; J < 5; J + +) { - System.out.println (C2.next ()); - } - } A +}
Operation Result:
localcount () counterlocal inner:0Local inner:1local inner:2local inner:3 Local Inner:4Anonymous inner:5Anonymous inner:6Anonymous inner:7Anonymous Inner :8Anonymous inner:9
In the code, counter returns the next value in the sequence. We use local inner classes and anonymous inner classes respectively to implement this function, which have the same behavior and methods. Since the name of the local inner class is not visible outside the method, why do we still use the local inner class instead of the anonymous inner class? The only reason is that we need an already named constructor, or we need to overload the constructor, and the anonymous inner class can only be used for instance initialization, so another reason to use the local inner class instead of the anonymous inner class is that more than one inner class object is required.
Comparison of local inner classes and anonymous inner classes