Article published: chesheng913
Published: 2004-07-30
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, 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 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, 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 simple, don't explain, you should also Can 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 overwrites the PRINT method of the parent class, which first do its own thing, 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 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, 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 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 ());
//b.i=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.linkedList
I = 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 ics {
ICLASS () {
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 final data";
Final
public
Void print () {
System.out.println (
Final Method. ");
}
public
Void what () {
System.out.println (STR
"/ n" str1);
}
}
public
Class FinalDemo {
// Extends final unable to inherit
public
Static
Void main (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.
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.