Thinking: STATIC, THIS, Super, FINAL Usage in Java

xiaoxiao2021-03-06  123

This article is intended to help prepare for Java and have a friend who just contact Java, mastering and using Static, this, super, final these keywords. Java is profound, I am also a fan who is learning and using Java, and there is still something wrong in the article. Welcome to correct. First, Static ???? Please look at the following program: ?? public? Class? Hello {???? public? Static? Void? Main (String []? Args) {? // (1)

?????? system.out.println ("Hello, World!"); ??? // (2)

????} ??} I have seen this program. For most learned Java?, It is not strange. Even if you haven't learned Java, you have learned other advanced languages, such as C, then you should also understand this code. It is just a simple output "Hello, World", nothing else, but it shows the main usage of Static keywords. At 1, we define a static method called main, which means telling the Java compiler, I can use this type of object to be used. Do you have to run this program? Generally, we are all under the command, and we will enter the following command (with the overline to manually enter):

Javaac? Hello.javajava? HelloHello, World! This is the process you run, the first line is used to compile hello.java files, after execution, if you check the current, you will find more helpo.class files, that is The Java binary item code generated by the first line. The second line is the most common approach to executing a Java program. Executive results are as expected. In 2, you may think, why do you want to output it. Ok, let's break down this statement. (If you do not install a Java document, please visit the J2se? API to Sun's Official Website) First, System is a core class in the java.lang package. If you view its definition, you will find this: public? Static Final? printstream? out; then click on the PRINTSTREAM hyperlink, in the Method page, you will see a lot of defined methods, find Println, there will be such a line: public? x). Ok, now you should understand why we want to call, OUT is a static variable of System, so you can use it directly, and the class belonging to the OUT has a PrintLn method. Static method usually, define a method in a class to static, that is, this method can be called without this class. As shown below: Class? Simple {??? static? Void? Go () {????? system.out.println ("go ..."); ???}} public? Class? CAL {? PUBLIC? Static? Void? main (string []? args) {???? simple.go (); ??}} Calling a static method is "Classification. Method name", the use of static methods is simple Indicated. In general, static methods often provide some utility to other classes in the application, and a large number of static methods in Java libraries are defined for this purpose. Static variable static variables are similar to the static method. All such instances share this static variable, that is, when the class is loaded, only one storage space is assigned, all such objects can be manipulated this block storage space, of course, for Final. Look at the following code: class? Value {?? static? Int? C = 0; ?? static? Void? Inc; ??}} Class? Count {?? public? Static? Void? PRT (String? s) {???? system.out.println (s); ??} ?? public? static? void? main (string []? args) {???? value? V1, V2; ???? v1 = new? Value (); ???? v2 = new? value (); ???? PRT ("v1.c =" v1.c "? v2.c =" v2.c); ???? v1.inc (); ???? PRT ("v1.c =" v1.c "? v2.c =" v2.c); ???? }} The result is as follows: v1.c = 0 ?? v2.c = 0v1.c = 1 ?? v2.c = 1 This thereby can prove that they share a memory area. The Static variable is a bit similar to the concept of global variables in C. It is worth exploring the initialization problem of static variables.

We modify the above program: class? Value {?? static? Int? C = 0; ?? value () {???? c = 15; ??} ?? Value (int? I) {???? C = i; ??} ?? static? void? inc () {???? c ; ??}} Class? count {?? public? static? void? PRT (String? s) {???? System.out.println (s); ??} ???? Value? V = new? Value (10); ???? static? Value? V1, v2; ???? static {????? ? PRT ("v1.c =" v1.c "? v2.c =" v2.c); ?????? v1 = new? value (27); ?????? PRT ( "v1.c =" v1.c "? v2.c =" v2.c); ?????? v2 = new? Value (15); ?????? PRT ("V1. C = " v1.c "? v2.c = " v2.c); ????} ?? public? static? void? main (string []? args) {???? count? CT = new? count (); ???? PRT ("ct.c =" ct.vc); ???? PRT ("v1.c =" v1.c "? v2.c =" v2.c); ???? v1.inc (); ???? PRT ("v1.c =" v1.c "? v2.c =" v2.c); ???? PRT ("ct.c =" ct.vc); ??}} The result is as follows: v1.c = 0 ?? v2.c = 0v1.c = 27 ?? v2.c = 27v1.c = 15 ?? v2.c = 15ct.c = 10v1.c = 10 ?? v2.c = 10v1.c = 11 ?? v2.c = 11ct.c = 11 This program shows the various characteristics of static initialization. If you first contact Java, the result may be surprised. It may be confused by adding static brackets. The first thing to tell you is that the variable defined by static is preferred over any other non-Static variable, regardless of its order. As is shown in the program, although V appears in front of V1 and V2, the result is the initialization of V1 and V2 in front of V. At the static {followed by a code, this is used to initialize explicit static variables, which only initializes once, and when the class is loaded. If you can read and understand this code, you will help you understand the Static keyword. When it is involved in inheritance, it will initially initialize the static variable of the parent class, then the subclass is pushed. Non-static variables are not the subject of this article, do not do a detailed discussion here, please refer to Think? IN? Java explanation. Static class usually does not allow statements that are static, only one internal class can be. At this time, this statement is that the static internal class can be used directly as a normal class without an example of an external class.

As shown in the following code: public? Class? Staticcls {?? public? Static? Void? Main (string []? Args) {???? outercls.innercls? Oi = new? Outercls.innercls (); ??}} Class? Outercls {?? public? static? Class? Innercls {???? INNERCLS () {?????? system.out.println ("innercls"); ????} ???}} output As a result, as you expected: InnerCls and normal classes. For other uses of internal classes, please refer to the related chapters in Think? In? Java, this is not explained. Second, THIS? &? Super ???? in the previous one

In this discussion of the use of Static, we define methods or members with Static to provide some convenience to some extent it can be said to be similar to global functions and global variables in C language. However, it is not to say this convenience, you can use it everywhere, if so, you need to carefully consider whether you are using the object-oriented idea, whether your program is object-oriented. Ok, now I am now discussing the meaning and usage of these two keywords of this & super. In Java, this usually refers to the current object, and Super refers to the parent class. When you want to reference something of the current object, such as a method of the current object, or a member of the current object, you can use this to implement this purpose, of course, another purpose of this is to call the current object Another constructor, these will now be discussed. If you want to quote some of the parent class, it is not Super. Since THIS and Super have some of these features and the innate relationship, we discuss this piece, hoping to help you distinguish between them. The most common situation in the general method is that a certain name in your way has the same name as a member of the current object, at this time, in order not to confuse, you need to express the keywords to specify the keyword. You have to use a member, how to use "this. Member name", without this one of this is a ginseng. In addition, you can also use the "this. Method name" to reference a method of the current object, but this is not necessary, you can directly use the method name to access that method, the compiler will know that you want to call. that one. The following code demonstrates the above usage: public? Class? Demothis {?? private? String? Name; ?? private? Int? Age; ?? demothis (String? Name, int? Age) {???? setname Name);? // You can add this to call the method, like this: this.setname (name); but this is not necessary

???? setage (age); ???? this.print (); ??} ????? public? void? setName (String? Name) {???? this.name = name; // Here, you must specify you to reference a member variable

??} ?? public? void? setage (int? age) {???? this.pe = agn; ??} ?? public? void? print () {???? system.out.println (" Name = " Name "? Age = " agn); // Do not need this in this line, because there is no confusing thing

??} ?? public? static? void? main (string []? args) {???? demothis? DT = new? demothis ("kevin", "22"); ??}} This code is simple Don't explain, you should also understand. In the constructor you see this.print (), you can use print () instead of it, both effects. Let's modify this program to demonstrate the usage of Super. Class? Person {?? public? int? c; ?? private? string? name; ?? protected? void? setName (String? name) {???? this.name = name ; ??} ?? protected? void? setage (int? age) {???? this.pe = agn; ??} ?? protected? void? print () {???? system.out.println "Name =" Name "? Age =" AGE); ??}} public? Class? DEMOSUPER? EXTENDS? PERSON {?? public? Void? Print () {???? system.out.println (" DEMOSUPER: "); ???? super.print (); ??} ?? public? Static? Void? Main (string []? Args) {???? demoomuper? DS = new? Demoomuper ();? ??? DS.setname ("kevin"); ???? ds.setage (22); ???? ds.print (); ??}} In DEMOSUPER, the redefined print method overwritten the father The Print method of the class, which first does something yourself, then call the one that the parent class is overwritten. The output is indicated in this: DEMOSUPER: Name = Kevin? AGE = 22 This method is more commonly used. In addition, if the members of the parent class can be accessed by subclasses, then you can use it like this, use the "super parent class" way, but often you don't have to access the membership name in the parent class. . The constructor is a special method in the constructor, which is automatically called when the object is initialized. In the constructor, this and super have all the ways of using it, and it also has special places. Please see the example below: Class? Person {?? public? Static? Void? PRT (String? S) {? ??? system.out.println (s); ??} ?? Person () {???? PRT ("a? Person."); ??} ?? Person (String? Name) {??? ? PRT ("a? Person? Name? IS:" name); ??}} public? class? Chinese? EXTENDS? PERSON {?? chinese () {???? super (); ?? // call Parent class constructor (1) ???? PRT ("a? Chinese."); // (4)

??} ?? chinese (String? Name) {???? super (name); // Call the parent class with the same structural constructor (2)

???? prt ("his? Name? IS:" Name); ??} ?? Chinese (String? Name, int? AGE) {???? this (name); // Call the current same shape Constructor (3)

???? PRT ("His? Age? IS:" AGE); ??} ?? public? static? void? main (string []? args) {???? chinese? cn = new? Chinese ); ???? cn = new? Chinese ("kevin"); ???? cn = new? Chinese ("kevin", 22); ??}} In this program, this and super no longer Use "." To connect to a method or member as before, but it has followed the appropriate parameters, so its meaning has changed. The SUPER will be used to call the same form of constructor in the parent class, such as 1 and 2. The THIS will be called, which is called the constructor of the currently the same parameter, such as 3. Of course, in each of the heavy-duty constructors of Chinese, THIS and Super are still useful in the general methods, such as 4, you can replace it to "this.prt" (because it inherits the parent class The method of "Super.PRT" (because it is the method in the parent class and can be accessed), it can operate correctly. But this seems to have a bit of painful taste. Finally, I have written so much. If you can refer to the current object, Super I usually refer to a single-child class ", then this article has achieved the purpose, and other self-programming practices Slowly experience, master. In addition, please refer to the related Java tutorial on the inheritance mentioned in this article. Third, Final

Final is not commonly used in Java, but it provides us with features such as defining constants in C language, not only that, Final also allows you to control your members, methods, or a class that can be overwritten or inherited, etc. Function, these features make Final have an indispensable status in Java, and one of the keywords that must be known and mastered when learning Java. Final Member When you define a variable in the class, add the final keyword in front, that is, once this variable is not changeable, this variable is not changeable, and the meaning of unable to change the basic type is not variable. And for object variables are not changeable. Its initialization can be in two places, one is its definition, that is, directly assigning it directly when the final variable is defined, and the other is in the constructor. These two places can only be selected, either giving value during defining, or give value in the constructor, not only giving value at the time of defining, and give additional values ​​in the constructor. The following code demonstrates this: import? Java.util.list; import? Java.util.ArrayList; import? Java.util.LinkedList; public? Class? Bat = 3.14 ;? ????????? // set the value when defined

????? final? Int? i; ???????????? // Because it is initialized in the constructor, it is no longer a value.

???? final? List? list; ???????? // This variable is also the same as the above

???? bat () {???????? i = 100; ???????? List = new? LinkedList (); ????} ???? bat (int? Ii , List? L) {???????? i = ii; ???????? List = L; ????} ???? public? Static? Void? Main (String [] ? args) {???????? bat? b = new? bat (); ???????? b.list.add (new? bat ()); ??????? ? // bi = 25;

???????? // b.list = new? arraylist ();

???????? system.out.println ("i =" b.i "? List? Type:" b.List.getClass ()); ???????? b = new ? Bat (23, new? Arraylist ()); ???????? b.list.add (new? Bat ()); ???????? system.out.println ("i = " B.I "? List? type: " b.List.getClass ()); ????}} This procedure is simple to demonstrate the general usage of Final. This is used here to initialize the initialization in the constructor, which makes you a little flexibility. As shown by the two overload constructors of the BAT, the first default constructor provides you with the default value, and the overloaded constructor is initialized according to the value of the value you provide or type. However, sometimes you don't need this flexibility, you only need to give its values ​​and never change when defined, do not use this method. There are two lines of statement in the main method. If you go to the comment, the program can't be compiled, this is to say, whether it is the value of I or the type of List, it is indeed possible to change. However, B can specify the value of i or the type of LIST by reinitialization, and this is displayed in the output: i = 100? List? Type: class? Java.util.LINKEDLISTI = 23? List? Type: Class? Java. Util.arrayList has another usage is that the parameter in the definition method is FINAL, for the basic type of variable, this does not do actual meaning, because the basic type of variable is transmitted when the call method is called, that is, you can This parameter variable is changed without affecting the calling statement, but for object variables, it is very practical because the object variable is transmitted at the time of delivery, so that you can modify the object variable in the method will also affect the call. Object variables in the statement, when you do not need to change object variables as parameters in the method, explicitly use Final declaration to prevent you from being unintentionally modified to affect the calling method. In addition, internal classes in the method are in addition to the parameters in the method, this variation must also be declared as FINAL can be used, as shown in the following code: public? Class? Inclass {??? void? InnerClass (Final? String? Str) {???????? Class? iClass {???????????? ICLASS () {???????????????? System.out .println (str); ?????????????} ???????}? IC = new? iClass (); ???? } ?? public? static? void? main (string []? args) {?????? inclass? inc= new? inclass (); ?????? inclass ("hello");? ?}} finary method declares the method as final, then you know that the features you have provided by this method have met you requires that there is no need to expand, and any classes from this kind of inheritance will override this method, but inheritance It can still inherit this method, that is, can be used directly.

There is another mechanism called inline, which will cause you to insert the method body directly into the call when calling the final method, not the routine method call, such as the saving breakpoint, stack, etc., this may Make your program efficiency, however, when your method is very large, or call this method in multiple places, then your call principal code will expand quickly, maybe it will affect efficiency, so you should use it with caution Final is defined. Final Category When you use Final to be used for classes, you need to carefully, because a Final class cannot be inherited by anyone, that means this class is a leaf class in one inheritance tree, and this class The design has been considered perfect without modifying or expanding. For members in the Final class, you can define it for Final or not Final. For the method, since the relationship between the class fina is, it naturally has become Final type. You can also make it clear to the Final class with a Final, but this is obviously meaningless. The following program demonstrates the usage of the Final method and the final class: final? Class? Final {???? final? String? Str = "final? Data"; ???? public? String? Str1 = "non? Final? Data "; ???? final? public? void? print () {???????? system.out.println (" final? Method. "); ????} ???? public? Void? What () {???????? system.out.println (Str "/ n" str1); ????}} public? class? finalDemo? {????}? Final ? Cannot inherit ????? public? Static? Void? Main (string []? Args) {???????? final? F = new? Final (); ???????? f .what (); ???????? f.Print (); ????}} It can be seen from the program that the Final class is almost no different from the ordinary class, but it lost its inheritance. characteristic. The difference between the final method and the non-final method is also difficult to see from the procedure, just remember caution. Final in design mode is a mode in design mode called constant mode, which can be easily implemented in Java, which can be easily implemented in the Final keyword. The program used when explaining Final membership is a constant Mode example. If you are interested in this, you can refer to the "Java and Mode" book written by Dr. Yan Hong. So far, this, static, supert and final use have been finished. If you have been able to rush to these four keywords, you have been able to have a substantially mastered. However, anything in the world is not perfect, Java provides these four keywords, bringing great convenience to programmers, but not to let you use it everywhere, once the abuse process, It is appropriate to be counterproductive, so please be careful when using it.

转载请注明原文地址:https://www.9cbs.com/read-126369.html

New Post(0)