JAVA basics-Explanation of internal classes and explanation of java Basics
JAVA internal class description
In my other encapsulation of the three major java features, I will introduce a brief overview of java internal classes. Here I will have a detailed understanding of the use and application of java internal classes.
We know that internal classes can be divided into the following types:
- Member internal class
- Static internal class
- Internal method class
- Anonymous internal class
Here we will first use this classification to learn more about the situation of each internal class. Then summarize the internal classes.
I. Member internal class
Internal classMost commonIs the member internal class, also knownCommon internal class. Let's look at the following code:
The running result is:
From the code above, we can see that,Usage of internal classes of members:
1. The Inner class is defined inInternal,It is equivalent to the position of a Member variable of the Outer class., Inner class can be usedAny access controllerSuch as public, protected, and private.
2. the test () method defined in the Inner class can beDirect AccessData in the Outer class,Not Affected by Access Control OperatorsFor example, you can directly accessPrivate property
3. After the internal class of the member is defined,You must use an external class object to create an internal class object., AndNot directlyGo to a new internal class object, that is:Internal Class Object Name = External Class Object. new internal class ();
4. After compiling the above program, two. class files are generated.
The second is the. class file of the external class, and the first is the. class file of the internal class, that is, the. class file of the internal class of the member is always like this:External class name $ internal class name. class
In addition,Friendly reminder:
1. The external class isCannot be used directlyInternal class member and method drop. For example:
So how do external classes use internal class members and methods ??
A:You can first create an internal class object, and then access its member variables and methods through the internal class object.
When creating an internal class object, the Java compiler implicitly transfers the reference of its external Class Object and keeps saving it. In this way, internal class objects can always access their external class objects. This is also the reason why they must first create their external class objects to create an internal Class Object outside the scope of the external class.
2. If the external class and internal class haveSame member variables or methods, Internal classAccess your member variables or methods by defaultTo access the member variables of an external class, you can useThis keyword. For example:
Running result:
Ii. static internal class
Static internal class isStatic modifiedInternal class.FeaturesYes:
1. static internal classCannot be accessed directlyExternal classNon-static memberBut you can useNew External class (). Member.
2. If the static members of the external class and the members of the Internal classSame name, You canClass Name. static member"Access static members of the external class; if the static members of the external class and the member names of the internal class areDifferent, You canMember name"Directly call static members of an external class.
3. When creating static internal class objects, you canDirectCreateInternal Class Object Name = new internal class ();
Running result:
Iii. Internal methods
The internal class of the method is the class defined by the internal classMethod, The internal class of the method is only visible inside the method, that isOnly available in this method.
Be sure to note:Because the internal class of the method cannot be used outside the external class, the internal class of the MethodAccess Control Operators and static modifiers cannot be used.
Iv. Anonymous internal class
The anonymous class isA class with a name is not allowed.So there is no way to reference them. Must be createdNew statementTo declare them.
However, an anonymous internal class has the following prerequisites:It must inherit a parent class or implement an interface.
This requires another new statement, as shown below:
New <class or interface> <class subject>
The new statement in this formDeclare a new anonymous classFor a given classOr implement a given interface.He also creates a new instance of that class and returns it as the result of the statement. The class to be extended and the interface to be implemented are the operands of the new statement, followed by the subject of the anonymous class.
Note:The declaration of anonymous classes is implemented during compilation and instantiation is implemented at runtime.This means that a new statement in the for Loop will create several instances of the same Anonymous class, rather than creating several instances of different anonymous classes.
Technically, anonymous classes can be considered non-static internal class, so they have the same permissions and restrictions as non-static internal classes declared in the method.
Assume that the task needs an object, but it is not worth creating a new object (probably because the required class is too simple or because it is only used within a method ), anonymous classes are very useful. Anonymous classes are especially suitable for quickly creating event handlers in Swing applications. The following is an example of an anonymous internal class:
1. Basic Implementation of anonymous internal classes:
Running result:
We can see that the methods in the abstract class Person are implemented in braces, so that the writing of a class can be omitted, and anonymous internal classes can also be used on interfaces.
2. Use an anonymous internal class on the interface:
Running result:
As shown in the preceding exampleA class is abstract or an interface., Then itsSubclass MethodYou can use anonymous internal classes.
Pay attention to the following points when using anonymous internal classes:
1,When using an anonymous internal class, we must inherit a class or implement an interface, but the two cannot have both. At the same time, we can only inherit one class or implement one interface.
2,Constructors cannot be defined in anonymous internal classes.
3,The anonymous internal class cannot contain any static member variables or static methods.
4,The anonymous internal class is a local internal class (that is, the internal class of the method), so all restrictions on the local internal class also apply to the anonymous internal class.
5,An anonymous internal class cannot be abstract. It must implement all the abstract methods of the inherited class or implemented interface.
Key challenges of anonymous internal class:
1. If it is in an anonymous internal class of a method, you can use this method to pass in the desired parameter, but remember,These parameters must be declaredFinal.
Why is final used ??
Reference blog: http://android.blog.51cto.com/268543/384844 http://blog.csdn.net/chenssy/article/details/13170015
When passing a parameter to an anonymous internal class, if the parameter needs to be used in the internal class, the parameter must be final. That is to say:When the parameter of the method needs to be used in the internal class, the parameter must be final.
First, we know that after the internal class is compiled successfully, it will generate a class file. This class file is not the same class file as the external class, but only retains the reference of the external class. When the parameters passed in by the external class need to be called by the internal class, the java program is called directly:
public class OuterClass { public void display(final String name,String age){ class InnerClass{ void display(){ System.out.println(name); } } } }
From the code above, it seems that the name parameter should be directly called by the internal class? Otherwise, the actual operations after java compilation are as follows:
public class OuterClass$InnerClass { public InnerClass(String name,String age){ this.InnerClass$name = name; this.InnerClass$age = age; } public void display(){ System.out.println(this.InnerClass$name + "----" + this.InnerClass$age ); } }
From the code above, the internal class does not directly call the parameters passed by the method, but uses its constructor to back up the input parameters, in fact, the internal method calls its own attributes instead of the parameters passed in by the external method.
Till now, I have not explained why final is used. Attributes in the internal class and parameters in the external method are the same in terms of appearance, but they are not actually, so they can be changed at will, that is to say, in the internal class, my changes to attributes will not affect the external parameters, which is not feasible from the programmer's point of view, after all, from the perspective of the program, the two are essentially the same. If the internal class changes, but the external method parameters do not change, this is hard to understand and unacceptable, therefore, to maintain the consistency of parameters, final should be used to avoid the constant change of parameters.
Simply put, copy references. In order to avoid changing the reference value, such as being modified by the external class method, internal classes get different values, so final is used to make the reference unchangeable.
Therefore, if you define an anonymous internal class and want it to use an externally defined parameter, the compiler will require that the parameter reference be final.
2. Use initialization code blocks in anonymous internal classes
We usually use the constructor to initialize an instance, but there is no constructor for anonymous internal classes! How can we initialize anonymous internal classes? Use to construct a code block! The construction code block can be used to create a constructor for an anonymous internal class.
Public class OutClass {public InnerClass getInnerClass (final int age, final String name) {return new InnerClass () {int age _; String name _; // construct a code block to complete initialization {if (0 <age & age <200) {age _ = age; name _ = name ;}} public String getName () {return name _;} public int getAge () {return age _ ;};} public static void main (String [] args) {OutClass out = new OutClass (); innerClass inner_1 = out. getInnerClass (201, "chenssy"); System. out. println (inner_1.getName (); InnerClass inner_2 = out. getInnerClass (23, "chenssy"); System. out. println (inner_2.getName ());}}5. Summary of internal categories
After learning the four types of internal classes above, we know how to use each internal class. Why should we use the internal class ??
Reference blog: http://blog.csdn.net/yu422560654/article/details/7466260
First, let's take a simple example. If you want to implement an interface, but a method in this interface has the same name and parameter as a method in the class you have conceived, what should you do? In this case, you can create an internal class to implement this interface. Since all the content of the internal class is accessible to external departments, this can achieve all the functions you directly implement this interface.
But you may have to question it. Isn't it enough to change the method? Indeed, there is no persuasion to use this as a reason for designing internal classes.
The real reason is that the internal classes and interfaces in java can be combined to solve a problem that C ++ programmers often complain about in java-there is not much inheritance. In fact, the multi-inheritance design of c ++ is very complicated, and java can implement multi-inheritance effectively by adding interfaces to internal classes.
Internal class: the definition of an internal class is defined in another internal class.
The reason is:
1. An internal class object can access the implementation of the object created for it, including private data.
2. For other classes in the same package, internal classes can be hidden.
3. Anonymous internal classes can easily define callbacks.
4. Use internal classes to easily write event drivers.
Internal classes allow you to design your program structure more elegantly. The following describes how:
First, let's look at this example:
1 public interface Contents { 2 int value(); 3 } 4 5 public interface Destination { 6 String readLabel(); 7 }
1 public class Goods { 2 private valueRate=2; 3 4 private class Content implements Contents { 5 private int i = 11 * valueRate; 6 public int value() { 7 return i; 8 } 9 } 10 11 protected class GDestination implements Destination { 12 private String label; 13 private GDestination(String whereTo) { 14 label = whereTo; 15 } 16 public String readLabel() { 17 return label; 18 } 19 } 20 21 public Destination dest(String s) { 22 return new GDestination(s); 23 } 24 25 public Contents cont() { 26 return new Content(); 27 } 28 }
In this example, the class Content and GDestination are defined inside the class Goods and have the protected and private modifiers respectively to control the access level. Content represents Goods Content, while GDestination represents Goods destination. They implement the Content and Destination interfaces respectively. In the following main method, you can directly use Contents c and Destination d to perform operations. You don't even see the names of these two internal classes! In this way,The first benefit of the internal class is embodied-hiding the operations you don't want others to know, that is, encapsulation.
Non-static internal class objects have references to their external class objects.
Modify the example above:
1 public class Goods { 2 private valueRate=2; 3 4 private class Content implements Contents { 5 private int i = 11 * valueRate; 6 public int value() { 7 return i; 8 } 9 } 10 11 protected class GDestination implements Destination { 12 private String label; 13 private GDestination(String whereTo) { 14 label = whereTo; 15 } 16 public String readLabel() { 17 return label; 18 } 19 } 20 21 public Destination dest(String s) { 22 return new GDestination(s); 23 } 24 25 public Contents cont() { 26 return new Content(); 27 } 28 }
Here we add a private member variable valueRate to the Goods class, which indicates the value coefficient of the Goods. The value () of the Content Method of the internal class is multiplied when it calculates the value. We found that value () can access valueRate, which is alsoThe second benefit of the internal class-an internal class object can access the content of the external class object created for it, and even include private variables!This is a very useful feature that provides us with more ideas and shortcuts during design. To implement this function, internal class objects must have references pointing to external class objects. When creating an internal class object, the Java compiler implicitly transfers the reference of its external Class Object and keeps saving it. In this way, internal class objects can always access their external class objects. This is also the reason why they must first create their external class objects to create an internal Class Object outside the scope of the external class.
What I want to say: I spent a long time collecting information on the Internet for java internal classes, and I have a lot of questions about this part of learning, if you have any questions, please leave a message below. I will do my best to answer the question. If you have any improvement criticism, please correct me. Thank you!