Learn some of the basics of Java Harvest One (this, static, Super, Final)

Source: Internet
Author: User

the application of this keyword in the Java language

Apply one: Reference member variable

 Public class // defines a class whose name is student.   
Public // define a method, with the same name as the class, so it is a construction method This ("Luobo") //This is a call to the following constructor method with arguments } Public // defining a construction method with formal parameters }

As in this code above, there is a member variable name. At the same time there is a formal parameter in the method, and the name is names. Then the method passes the value of the form parameter name to the member variable name. Although we can see the meaning of this code, but as a Java compiler how is it judged? Is it true that the value of the formal parameter name is passed to the member variable name, or the value of the member variable name is passed to the formal parameter name? That is, if the two variable names are the same, So how does Java determine which variable to use? This keyword will play a role. This keyword represents a member variable or method in an object. That is, if you precede a variable with the This keyword, it refers to the member variable or method of the object, not the formal parameter or local variable of the member method . In this code above, THIS.name represents the member variable in the object, also called the property of the object. The following name is the formal parameter of the method. The code this.name=name is to pass the value of the formal parameter to the member variable. This is exactly what the above code means.

In general, referencing member variables or member methods in the Java language is the object name. A member variable or an object name. The form of a member method. However, some programmers prefer to use this as a member variable, even when they do not have the same variable. This is mainly from the convenience of reading the code to consider. As soon as you see this keyword, you know that the variable you are referencing is either a member variable or a member method, not a local variable. This virtually improves the readability of the code. But then again, this is the simplest application of the This keyword in the Java language. From this application, we can see that the This keyword represents the name of the object. Once you have mastered this basic principle, learn about some of the next high-level applications, which are the things that come naturally.

Here I just take a formal parameter as an example. In fact, if it is a local variable, it is the same reason. As in the above code, name is not a formal parameter, but a local variable. Java will also encounter the same doubts, that is, the variable name name is a local variable or formal parameters? What does name=name mean? According to the scope of the local variable, inside the method, if the local variable has the same name as the member variable, the local variable will prevail. However, in Name=name this assignment statement, it is obviously not appropriate to assign the value of the local variable to itself. According to the meaning of the code, the original meaning should be to assign a local variable to the member variable. In order to express this meaning more clearly, it is best to use the following writing format: This.name=name. The This keyword here means the object name student. For this reason, THIS.name represents Student.name. This translates to a formal member variable applied.

Application two: Constructing method of calling class

this ("Luobo") is called the
Public Student (String name) method

Apply three: Return the value of an object

The This keyword, in addition to referencing variables or member methods, has a significant effect of returning a reference to a class. As in code, you can use return this to return a reference to a class. At this point, the This keyword represents the name of the class. If this code is in the student class above, then this code represents the meaning of return student. This keyword can be seen as a return value for a class, in addition to referencing variables or member methods. This is where the This keyword is most noticeable.

When you use the This keyword, you need to be aware of a detail issue. In the first case I talked about, we used the This keyword to refer to member variables. That is this.name=name. This statement assigns a local variable or form parameter to a member variable. In fact, at this point this keyword does not add can also play a similar effect. This is the same statement as the Name=name statement. That is, the Java compiler automatically treats the first name as a member variable. Instead, the name variable to the right of the equal sign is treated as a formal parameter. While writing code like this, you can save the input for this few characters. But the reading of the code is unfavorable. For this reason, from the reading of the code, if the member variable is the same as the formal parameter or local variable, it is best to use this. Member variable (member method) to refer to the member variable. There is no grammatical error, but as a high-level Java programmer, it cannot be overlooked in the code writing specification.

application of static keyword in Java language

Invoking a static method is "class name. Method Name", and the use of static methods is simple as shown above. In general, static methods are often used by other classes in the application, and in Java's class libraries a large number of static methods are defined for this purpose.


static variables

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 allocated, and all objects of this class can manipulate this block of storage space, although for final it is a matter of course . Look at the following code:

classvalue{Static intC=0;Static voidInc () {C++;}}classcount{ Public Static voidprt (String s) {System.out.println (s);} Public Static voidMain (string[] args) {Value v1,v2;v1=NewValue (); V2=NewValue ();p RT ("V1.c=" +v1.c+ "v2.c=" +v2.c); V1.inc ();p RT ("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

Analysis of Super keyword application in Java language

1 classperson{2  Public intC;3 PrivateString name;4 Private intAge ;5 protected voidsetName (String name) {6  This. name=name;7 }8 protected voidSetage (intAge ) {9  This. age=Age ;Ten } One protected voidprint () { ASystem.out.println ("name=" +name+ "age=" +Age ); - } - } the  Public classDemosuperextendsperson{ -  Public voidprint () { -System.out.println ("Demosuper:"); - Super. Print (); + } -  Public Static voidMain (string[] args) { +Demosuper ds=NewDemosuper (); ADs.setname ("Kevin"); atDs.setage (22); - ds.print (); - } -}

In Demosuper, the redefined Print method overridden The Print method of the parent class, first doing something of its own, and then invoking the overridden method of the parent class. The output illustrates this point:


Demosuper:
Name=kevin age=22

The use of this method is more commonly used. In addition, if a member of the parent class can be accessed by a class, you can use it like this, using the "super. Member name in the parent class" way, but often you do not have access to the member names in the parent class.

In the constructor

A constructor is a special method that is called automatically when an object is initialized. In the constructor, this and super also have a variety of ways to use the above, and it has a special place, see the following example:

classperson{ Public Static voidprt (String s) {System.out.println (s);} Person () {PRT ("A person.");} Person (String name) {PRT (' A person name ' is: ' +name);}} Public classChineseextendsPerson{chinese () {Super();//calling the parent class constructor (1)PRT ("A Chinese.");//(4)}chinese (String name) {Super(name);//calling a constructor with the same formal parameters as the parent class (2)PRT ("His name is:" +name);} Chinese (String name,intAge ) { This(name);//call the constructor that currently has the same formal parameter (3)PRT ("His age is:" +Age );} Public Static voidMain (string[] args) {Chinese CN=NewChinese (); CN=NewChinese ("Kevin"); CN=NewChinese ("Kevin", 22);}}

In this program, this and super are no longer used as before. Connect a method or member, but follow the appropriate parameters directly thereafter, so the meaning of it changes. Super is used to invoke constructors that have the same form in the parent class, such as 1 and 2. This is followed by a constructor that currently has the same parameters, such as 3. Of course, in the various overloaded constructors of Chinese, this and super are still available in various usages of the general method, such as 4 where you can replace it with "this.prt" (because it inherits that method from the parent class) or "Super.prt" (because it is a method in the parent class and can be accessed by the class), it works correctly. But it seems to be a little superfluous flavor.


Finally, write so much, if you can "this usually refers to the current object, super usually refers to the parent class" This sentence to keep in mind, then this article will achieve the goal, other you will be in the future programming practice slowly experience, master. See also the related Java tutorials for the inheritance mentioned in this article.

application of final keyword in Java language

Final is not commonly used in Java, but it gives us the ability to define constants in the C language, and final allows you to control your members, methods, or whether a class is capable of overwriting or inheriting , These features make final an integral part of Java and one of the key words that you must know and master when learning java.

Final member

When you define a variable in a class and precede it with the final keyword, it means that once the variable is initialized it is immutable, and the immutable meaning is immutable for the base type, and the reference to the object variable cannot be changed. Its initialization can be in two places, one is its definition, that is, when the final variable is defined directly assigned to it, and the second is in the constructor. These two places can only be selected, either in the definition of the value, or in the constructor to give a value, not both in the definition of the value, but also in the constructor to give another value. The following code demonstrates this:

Importjava.util.List;Importjava.util.ArrayList;Importjava.util.LinkedList; Public classbat{Finalpi=3.14;//address value when definedFinal intI//because you want to initialize in the constructor, you can't give the value hereFinalList List;//This variable is also the same as aboveBat () {i=100; list=NewLinkedList ();} Bat (intii,list L) {i=ii;list=l;} Public Static voidMain (string[] args) {Bat b =NewBat (); B.list.add (NewBat ());//b.i=25;//b.list=new ArrayList ();System.out.println ("i=" +b.i+ "List Type:" +B.list.getclass ()); b =NewBat (23,NewArrayList ()); B.list.add (NewBat ()); System.out.println ("I=" +b.i+ "List Type:" +B.list.getclass ());}}

This program is a simple demonstration of the general use of final. Here you have a bit of flexibility by using methods that are initialized in the constructor. As shown in the two overloaded constructors for bat, the first default constructor gives you the default value, and the overloaded constructor initializes the final variable based on the value or type that you provide. However, sometimes you don't need this flexibility, you just need to give it a value when you define it and never change it. There are two lines in the main method commented out, if you remove the comment, the program will not be compiled, this is to say, regardless of the value of I or the type of list, once initialized, can not be changed. However, B can be re-initialized to specify the value of I or the type of list, which is shown in the output:


i=100 List Type:class java.util.LinkedList
i=23 List Type:class java.util.ArrayList

Another usage is that the parameter in the definition method is final, and for a variable of the basic type, this does not make any sense, because a variable of the underlying type is passed at the time the method is called, which means that you can change the parameter variable in the method without affecting the calling statement, but for the object variable, is useful, because object variables pass their references when they are passed, so that your modification of the object variable in the method also affects the object variable in the call statement, and when you do not need to change the object variable as an argument in the method, explicitly using final declaration will prevent you from inadvertently modifying the calling method.
In addition, when an inner class in a method is used with a parameter variable in a method, this parameter must also be declared final to be used, as shown in the following code:

 public  class   inclass{ void  innerclass (final   String str) { class   Iclass{iclass () {System.out.println (str);}} IClass IC  =new   IClass ();}  public  static  void   main (string[] args) {inclass inc  =new  Span style= "color: #000000;" > Inclass (); Inc.innerclass ( "Hello" );}}  

Final method


Declaring the method as final means that you already know that the functionality provided by this method satisfies your requirements, does not need to be extended, and does not allow any class inheriting from this class to overwrite the method, but inheritance can still inherit this method, which means that it can be used directly. There is also a mechanism called inline, which allows you to insert the method body directly into the call when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, and so on, which may improve your program efficiency, but when your method body is very large, Or you call this method in many places, then your calling body code will quickly expand, it may affect efficiency, so you should be careful to use final method definition.

Final class

When you use final for a class, you need to think carefully, because a final class cannot be inherited by anyone , which means that the class is a leaf class in an inheritance tree, and that the design of such a class is considered perfect without the need for modification or extension. For members in the final class, you can either define it as final or not final. And for the method, because the class is the final relationship, Nature will become final type. You can also explicitly add a final to the method in the final class, but this is obviously meaningless.

The following program demonstrates the use of the final method and the final class:

Final class Final{FinalString str= "Final Data"; PublicString str1= "Non final Data";Final  Public voidprint () {System.out.println ("Final method.");} Public voidWhat () {System.out.println (str+""+STR1);}} Public classFinaldemo {//extends final cannot inherit Public Static voidMain (string[] args) {Finalf=New Final(); F.what (); F.print ( );}}

The above is my recent learning experience, the original author is too good, so basically did not modify, the original address is as follows:

Http://www.cnblogs.com/-cyb/articles/Java-this.html

Http://www.cnblogs.com/wjun530/archive/2007/09/15/893802.html

Learn some of the basics of Java Harvest One (this, static, Super, Final)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.