In Java class in the definition of class, this in other class inner class is called inner class, the most common in Android development three kinds of internal classes are (member inner class, method inner class, Anonymous inner Class)
First, members of the internal class
Class Test {2 // non-open class memberinnerclass{void Memberinner () {5 SYSTEM.OUT.PRINTLN ("Member inner Class"); } }8}
Compiled, we see that there are two class files in the directory in our working directory, you can see more than one Test$memberinclass.class file, this is the internal class after the compiled classes file
Features of the members inner class:
- An inner class exists in an external class just like an instance member.
- An inner class can access all members of an external class without restriction, just like accessing its own members.
- This in the inner class refers to the instance object itself of the inner class, which can be obtained by using the class name. This method if you want to use an instance object of an external class.
- There cannot be static members in an inner class object for the simple reason that an instance object of an inner class is a member of an external class instance object.
Ii. internal classes of methods
Class A {void A () {4 System.out.println ("Method inner Class"); } 7}
1public class Test { 2 3 public void Methodinner () { 4 // transient 5 class B extends a{ 6 7 } 8 new B (). A (); 9 }10}
Method Inner class features:
- The inner class in the method does not have an access modifier, that is, the inner class of the method is not visible to anything other than the method that surrounds it.
- The inner class of a method can only access local variables in the method, so it is also called a local inner class. And these local variables must be final-modified constants.
Iii. Anonymous internal class (the most common one in Android)
When we write the definition and declaration of the inner class together, we don't have to give the Class A class name but use it directly, and this kind of inner class has no class name at all, so we call it anonymous inner class
Implements b{void A () {4 System.out.println ("a"); 7}
Interface b{2 void B (); 5}
1PublicClassTest {23PublicStaticvoidMain (string[] args) { 4 //new out interface or implementation class 5 a a= new A () { 6 // Implementing methods not implemented in interfaces 7 public void B () { 8 System.out.println ("Anonymous inner class" 9 }10 };11 A.A (); a.b ()
Characteristics of anonymous inner classes:
- A class is used to inherit other classes or implement interfaces, and there is no need to add additional methods, just prior or overwriting the inherited methods.
- Just to get an object instance, you don't need to know its actual type.
- The class name is meaningless, that is, it does not need to be used.
Android common three kinds of internal classes