STATIC, THIS, Super, Final Usage in Java

zhaozj2021-02-16  72

http://blog.9cbs.net/chensheng913/Archive/2004/07/05/34564.aspx

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 Hello

Hello, 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 below this 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 = 0

v1.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.v.c);

PRT (

"v1.c =" v1.c

"V2.c =" v2.c);

v1.inc ();

PRT (

"v1.c =" v1.c

"V2.c =" v2.c);

PRT (

"ct.c =" ct.v.c);

}

}

The results of the operation are as follows:

v1.c = 0 v2.c = 0

v1.c = 27 v2.c = 27

v1.c = 15 v2.c = 15

Ct.c = 10

v1.c = 10 v2.c = 10

v1.c = 11 v2.c = 11

Ct.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

In the previous article, we discussed the use of Static, defined methods or members with Static, providing some convenience to our programming, from some extent, it can be said to a global function and global in C language 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 demothis {

Private string name; private

Int agec;

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 (agn);

this.print ();

}

public

Void setName (String name) {

THIS.NAME = Name;

/ / Must indicate you to reference a member variable here

}

public

Void setage

INT AGE) {

THIS.AGE = AGE;

}

public

Void print () {

System.out.println (

"Name =" Name

"AGE =" AGE);

// Don't use this in this line, because it doesn't cause confusion

}

public

Static

Void main (string [] args) {

Demothis DT =

New demothis

"Kevin",

"twenty two");

}

}

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 agec;

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 Demosuper

Extends persons {

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);

}

Person () {PRT

"A person.");

}

Person (String name) {

PRT (

"A Person name is:" name);

}

}

public

Class Chinese

Extends persons {

CHINESE () {

Super ();

// Call the 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 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 are no longer used as "." To connect to 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.

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

New Post(0)