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 process, and I have never been strange for most learned Java. 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 defined a static method called Main, which means telling the Java compiler, I can use this method to use such objects. Do you have to run this program? In general, we are all under the command, and we will enter the following command (to enter the line to manually enter): Javac Hello.javajava Hellohello, World! This is the process you run, the first line is used to compile hello.java file, After the execution, if you look at the current, you will find more hello.class files, which 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 in further, click on PrintStream this hyperlink, in the Method page, you will see a lot of defined methods, find Println, there will be such a line: public void println (String 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 as shown above. 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 () {C ;}} 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 can prove that they share a storage 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 operation results are 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 demonstrates 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, and don't do a detailed discussion here, please refer to the explanation in Think in Java. 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");}}}

The output result is as you expected: InnerCls and ordinary classes. For other usages of the internal class, please refer to the relevant chapters in Think in Java, which is not explained here. Second, THIS & Super In the previous article, we discussed all the use of Static, defined methods or members with Static, providing some convenience to our programming, from some extent, it can be said to be similar to C language Global function and global variables. 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 demoth {private string name; private int agent; demothis (String name, int agent) {setName (Name); // You can add this to call the method, like this: THIS .setname (name); but this is not a must setage (AGE); this.print ();} public void setName (String name) {this.name = name; // must specify you to reference member variables} Public void setage {this.pe = age;} public void print () {system.out.println ("name =" Name "Age =" AGE); // does not need in this line With this, because there is no confusing thing} public static void main (string [] args) {demoth DT = new demothis ("kevin", "22");}}

This code is very simple, you should also understand it without explaining. 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; private int age; protected void setName (String name) {this.name = name;} protected void setAge (int age) {this.age = age;} protected void print () {System.out.println ("Name =" Name "Age =" AGE);}} public class demoomuper extends Person {public void print () {system.out.println ("Demosuper:"); super.print (); Public static void main (string [] args) {DEMOSUPER DS = new demosuper (); ds.setname ("kevin"); DS.SETAGE (22); ds.print ();}}

In DemoSuper, the redefined print method overrides the parent class's Print method, which first do its own thing, then call the one-written method of the parent class. 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 mentioned above, and it also has special places, please see the example below: Class Person {public static void pr (String s) {system.out.println (s) Person () {PRT ("a person) {PRT (" a person name is: " name);}} public class Chinese extends Person {Chinese () {super () {super () {super () ; // Call the parent class constructor (1) PRT ("a Chinese."); // (4)} Chinese (String Name) {super (name); // Call the parent class has the same structural constructor ( 2) PRT ("His Name is:" Name);} Chinese (String Name, INT AGE) {this (name); // Call the constructor (3) PRT ("His Age IS: " AGE);} public static void main (string [] args) {Chinese cn = new Chinese (); cn = new Chinese (" kevin "); cn = new Chinese, 22);}} In this program, THIS and Super are no longer as used as previously "." To connect a method or member, but directly following 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 {final pi = 3.14; // Added value Final Int i; // Because it is initialized in a constructor, it is no longer a value of Final List List; // This variable is also the same 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 ba ()); / / 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 the value of i or the type of List, the output result is displayed in the output: i = 100 list type: class java.util.LinkedListi = 23 list type: Class Java.util.arraylist is also Usage is that the parameters in the definition method are final, for basic type variables, this does not do actual meaning, because the basic type of variable is a pass value when the method is called, that is, you can change this parameter variable in the method. Not affecting the calling statement, but for object variables, it is very practical because object variables are passed to deliver them, so that you can modify the object variable in the method also affect the object variables in the call statement. When you don't need to change object variables as a parameter in the method, you will explicitly use the final declaration to prevent you from being unintentionally modified to affect the calling method. In addition, internal classes in the method are in the method in the method, and this variation must also be declared to Final to use, as shown in the following code: public class inclass {void innerclass (final string str) {class oclass {ivlass ) {System.out.println (STR);}} iClass IC = New iClass ();} public static void main (string [] args) {inclass inc = new inclass (); Inc.innerClass ("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 you don't need to expand, and you don't allow any classes from this kind of inheritance to override this method, but inherit is still It can 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 final methods and final class: Final Class Final {Final String Str = "Final Data"; public string str1 = "non factory"; final public void print () {system.out.println (" Final method. "); {Final f = new femivity (); 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 has lost the characteristics of the inheritance. 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-126580.html

New Post(0)