[Repost] Original
http://www.9cbs.net/news/newspaper.asp?id=17061
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 programs first:
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? Generally, we are all under the command, and we will enter the following command (with the overline to manually enter):
Javac Hello.javajava Hellohello, World!
This is the process you run, the first line is used to compile the hello.java file, after execution, if you see the current, you will find more hello.class files, that is the first line generated Java binary bytecode . 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
Typically, a method is defined in a class for static, that is, this method can be called without the object of this class. As follows:
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 static methods. 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 results are as follows:
v1.c = 0 v2.c = 0V1.c = 1 v2.c = 1
This can be proved to 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 procedures:
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 results of the operation 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 shows the various features 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 a normal class is not allowed to be 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. The following code shows:
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
Like a general class. 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 the use of Static, defined methods or members with Static, providing some convenience for our programming, from some extent, it can be said to be similar to global functions in the C language and Global variable. 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.
In general methods
The most common situation is that there is the same name as a member of your way to a member of the current object, at this time, in order not to confuse, you need to express the THIS keyword to indicate that you want to use Members, how to use is "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 usage:
Public class demoth {private type; private int agent; demoth (String name, int agent) {setName (name); // You can call the method, like this: this.setname (name); but this Not a must setage; this.print ();} public void setName (String name) {this.name = name; // must specify you to reference member variables} public void setage {THIS .age = age;} public void print () {system.out.println ("name =" name "AGE =" AGE); // Do not need this in this line, because it is not confusing Public static void main (string [] args) {demoth 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; 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 illustrated in this:
DEMOSUPER: Name = kevin agn = 22
Such methods are 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. .
In the constructor
The constructor is a special method that is automatically called when the object is initialized. In the constructor, this and super also have all the ways mentioned above, and it also has special places, please see the example below:
Class Person {public static void prt (string s) {system.out.println (s);}}} () {PRT ("a person) {PRT (" a person name is: " Name);}}}} public class Chinese extends Person {Chinese () {super (); // Call the parent class constructor (1) PRT (" a Chinese. "); // (4)} chinese ) {Super (name); // Call the parent class with the constructor (2) PRT ("his name is:" name);} Chinese (String Name, int Age) {this (name); / / Call the current 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 used as "." to connect to a method or member, but directly 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, that is, once this variable is not changed, this variable is not changeable, and the meaning of unable to change is not variable, for the basic type. 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 of the constructor In initialization, 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 ba (); 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 program is very simple demonstration Final General usage. 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
There is also an usage to define the parameters in the method to final, for basic type variables, do not do this, because the basic type of variable is transmitted when the method is called, that is, you can change in the method. This parameter variable does not affect the calling statement, but for object variables, it is very practical because object variables are passed to deliver their reference, so that your modification of object variables in the method also affects the calling statement Object variables, when you do not need to change object variables as parameters in the method, explicitly use Final declaration, prevent you from unintentional to affect the calling method. In addition, the internal classes in the method are in the amount of the parameter 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 ket i {ivlass () {system.out.println (STR);}} iClass IC = new iClass ();} public static void main (String [] args) { INCLASS INC = New Inclass (); Inc.innerClass ("Hello");}} final method
Declaring the method as Final, then you already know that the functionality provided by this method has met your request, no need to expand, and do not allow any classes from this type to override this method, but inheritance can still inherit this method. That is to say, it 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 class
When you use Final for class, 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 type of design It has been considered perfect without modification or expansion. 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 factory"; final public void print () {system.out.println ("Final Method.");} public void what () { System.out.println (Str "/ N" str1);}} public class finaldemo {// extends final (String [] args) {final f = new final (); f.What ); F.print ();}}
As can be seen from the program, the Final class is almost no different from 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.
Application of Final in design mode
In the design mode, there is a pattern called constant mode. This mode can be easily implemented in Java, which is easy to implement, and the program used when explaining Final members 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.