Static, this, super, final usage in Thinking:java

Source: Internet
Author: User
Tags define definition execution final functions variables static class variable

Static, this, super, final usage in Thinking:java







This article is designed to help people who are ready to learn Java and just contact Java to recognize, master, and use the static, this, super, final, and other keywords. Java profound, I am also a learning and use of Java enthusiasts, the article is inevitable there is something wrong, welcome to correct.



One, static



Please read the following procedure:



public class hello{public static void Main (string[] args) {//(1) System.out.println ("hello,world!"); (2)}}



Read this program, for most of the learning Java from, are not unfamiliar. Even if you haven't studied Java and learned other high-level languages, such as C, you should be able to read the meaning of this code. It is simply the output "Hello,world", which has no other use, however, it shows the main use of the static keyword.



At 1, we defined a static method named Main, which means telling the Java compiler that I do not need to create an object of this class to use. How do you have to run this program? In general, we are all at the command line, into the following command (underlined for manual input):



Javac Hello.javajava hellohello,world!



This is the process you run, the first line to compile Hello.java This file, after execution, if you look at the current, you will find a more Hello.class file, that is the first line of Java binary bytecode generated. The second line is the most common way to execute a Java program. The execution results are as you expected. In 2, you might think, why do you have to output this way? OK, let's break down this statement. (If you don't have a Java document installed, go to Sun's official website to browse the J2SE API) first, system is a core class in the Java.lang package, and if you look at its definition, you'll find one line: public static final PrintStream out; Then in the further, click PrintStream This hyperlink, on the method page, you will see a number of defined methods, find println, there will be such a line:



public void println (String x).



Well, now you should understand why we're calling it that out is a static variable of system, so it can be used directly, and the class that the out belongs to has a println method.



static method



Typically, you define a method as static in a class, that is, you can call this method without an object of 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 the "class name. Method Name", and the use of static methods is simple as shown above. In general, static methods often provide utilities for other classes in the application, and a large number of static methods are defined for this purpose in Java's class libraries.



static variables



Static variables are similar to static methods. All such instances share this static variable, that is, when the class is loaded, only a single storage space is allocated, and all objects of this class can manipulate this block of 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 prove that they share a storage area. A static variable is somewhat similar to the concept of a global variable in C. It is worth discussing 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.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=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 touch Java, the result may surprise you. It may be confusing to add parentheses after static. The first thing to tell you is that the static-defined variable takes precedence over any other non-static variable, regardless of the order in which it appears. As shown in the program, although v appears in front of V1 and v2, the result is V1 and V2 initialization in front of v. Following the static{followed by a code that is used for explicit static variable initialization, which is initialized only once, and when the class is first loaded. If you can read and understand this code, it will help you understand the static keyword. When it comes to inheritance, the static variables of the parent class are initialized, followed by subclasses, and so on. Non-static variables are not the subject of this article and are not discussed in detail here, please refer to the explanations in the thought in Java.



Static class



Typically, a generic class is not allowed to be declared static, and only one inner class is available. At this point, the internal class declared as static can be used directly as a normal class, without the need for an instance 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 will be as you would expect:



Innercls



Same as the ordinary class. For other uses of internal classes, refer to the relevant chapters in the "I" Java, which are not detailed here.



Second, this & super



In the previous flops, we discussed the various uses of static, by defining methods or members with static, which provided some convenience for us to program, and to some extent it was similar to global functions and global variables in C language. However, it is not said that with this convenience, you can use everywhere, if so, you need to seriously consider whether you are using object-oriented thinking programming, whether your own program is object-oriented. OK, now let's discuss the meaning and usage of the two keywords This&super.



In Java, this usually refers to the current object, and Super refers to the parent class. When you want to refer to 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 do this, and of course, another purpose of this is to call another constructor of the current object, which is about to be discussed immediately. If you want to refer to something of the parent class, it is not super. Since this and super have some of the same characteristics and innate relationships, we are here to discuss it, hoping to help you distinguish and master them two.



In the general method



The most common scenario is that a parameter name in your method has the same name as a member of the current object. In order to avoid confusion, you need to explicitly use the This keyword to indicate that you want to use a member, using the method "this. Member name", and the one without this is the formal parameter. In addition, you can use "this. Method name" to refer to a method of the current object, but this is not necessary, you can access that method directly with the method name, and the compiler will know what you are calling. The following code illustrates the above usage:



public class demothis{private String name;  private int age;    Demothis (String Name,int age) {SetName (name);//You can add this to invoke the method, like this: This.setname (name); But this is not necessarily setage (age);  This.print (); The public void SetName (String name) {this.name=name;//must indicate that you want to refer to the member variable} public void Setage (int age) {This.age=ag  E public void print () {System.out.println ("name=" +name+ "age=" +age);//This is not necessary in this line because there is nothing to cause confusion} public static Voi  D main (string[] args) {demothis dt=new demothis ("Kevin", "22"); }}



This code is simple, and you should be able to see it without explaining it. In the constructor you see the This.print (), you can use print () to replace it, the effect is the same. Here we modify this program to demonstrate the use 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 Demosuper 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 repeats the Print method of the parent class, which first does its own thing, and then invokes 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 access the quilt class, you can use it like this, using the "member name in Super. Parent class," but often you do not access the member names in the parent class in this way.



In the constructor



A constructor is a special method that is invoked automatically when an object is initialized. In the constructor, this and super also have the various uses described above, and it has a special place, please see the following example:



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 person{Chinese () {super (); Invokes the parent class constructor (1) PRT ("A Chinese.");  /(4)} Chinese (String name) {super (name);//Invoke constructor function (2) PRT with the same formal parameters as the parent class ("His name is:" +name);  } Chinese (String Name,int age) {This (name);//Invokes the constructor (3) PRT that currently has the same formal parameter ("the His": +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 the same as they used to be. To connect a method or member, but to immediately follow the appropriate parameters, so its meaning has changed. The super parameter is used to invoke constructors in the parent class that have the same form, such as 1 and 2. This parameter then invokes the constructor that currently has the same parameters, such as 3. Of course, the various uses of this and super in the general method are still available in the overloaded constructors of Chinese, such as 4 where you can replace it with "this.prt" (because it inherits the method in the parent class) or "Super.prt." (because it is a method in the parent class and can be accessed by the Quilt Class), it can still run correctly. But this seems to be a little more than the taste of the lily.



Finally, written so much, if you can "this usually refers to the current object, super usually refers to the parent class" This sentence to bear in mind, then this article has achieved the purpose, the other you will be in the future of programming practice slowly experience, master. Also for the inheritance mentioned in this article, see the related Java tutorial.



Third, final



Final is not used in Java, but it provides us with functions such as defining constants in C, and final allows you to control your members, your methods, or whether a class can be overwritten or inherited. These characteristics make final in Java has an indispensable position, but also learn Java must know and master one of the keywords.



Final member



When you define a variable in a class, precede it with the final keyword, that is, once the variable is initialized, it cannot be changed, and the immutable meaning here 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, the final variable is defined directly to its value, and the second is in the constructor. These two places can only be selected, either by giving values at the time of definition, or by giving values in the constructor, not both at the time the value is defined, and by giving another value in the constructor. This is illustrated by the following code:



Import Java.util.list;import Java.util.arraylist;import Java.util.linkedlist;public class bat{    Final pi=3.14;         //    final int i at definition;            //Because you want to initialize in the constructor, you cannot give the value back here      Final List list;       //This variable is also the same as above     Bat () {         i=100;        list=new linkedlist ();    }    Bat (int ii,list l) {        i=ii;         list=l;   }    public static void Main (string[] args) {& nbsp;       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 program is a simple demonstration of final general usage. This gives you a little flexibility by using the method of initializing in a constructor here. As shown in the two overloaded constructors of bat, the first default constructor gives you the default value, and the overloaded constructor initializes the final variable based on the value or type you provide. But sometimes you don't need this flexibility, you just need to define the value and never change it, then don't use this method. In the main method, there are two lines of comment out, if you remove the annotation, the program will not be compiled, which means that, whether it is the value of I or the type of list, once initialized, it can not be changed. However, B can be reinitialized to specify the value of I or the type of list, which is shown in the output result:



i=100 list Type:class java.util.linkedlisti=23 list Type:class java.util.ArrayList



Another use is to define that the parameters in the method are final, for a variable of the base type, this does not make any sense, because a variable of the base type is passed as a value when the method is invoked, which means that you can change the parameter variable in the method without affecting the calling statement, but it is useful for object variables. , because the object variable passes its reference when it is passed, so your modification of the object variable in the method also affects the object variable in the calling statement, and when you do not need to change the object variable as a parameter in the method, the explicit use of final declaration will prevent you from inadvertently modifying the calling method. In addition, when an inner class in a method uses a parameter variable in a method, the parameter must also be declared final before it can 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 inclass ();  Inc.innerclass ("Hello"); }}



Final method



Declaring a method final means that you already know that the method provides functionality that satisfies your requirements, does not need to be extended, and does not allow any class inherited from this class to overwrite this method, but inheritance can still inherit this method, which means it can be used directly. There is also a mechanism called inline, it will allow you to insert the method body directly into the call place when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, and so on, which may make your program more efficient, but when your method body is very large, Or if you call this method in more than one place, your calling principal code expands rapidly and may affect efficiency, so be careful to use final method definitions.



Final class



When you apply final to the class, you need to think about it, because a final class cannot be inherited by anyone, which means that this class is a leaf class in an inheritance tree, and that the design of this class has been considered perfect without any need for modification or extension. For a member of the final class, you can define it as final or not final. And for the method, because the class is final relationship, natural also become final type. You can also explicitly add a final to the method in the final class, but this obviously doesn't make sense.



The following program demonstrates the final method and the final class usage:



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 cannot inherit public static void Main (string[] args) {final f=new final ();        F.what ();    F.print (); }}



As you can see from the program, the final class is almost no different from the normal class, except that it loses its inherited attributes. The difference between final method and non final method is also difficult to see from the procedure line, just remember to use carefully.



The application of final in design pattern



In design mode, there is a pattern called invariant mode, in Java through the final keyword can easily implement this pattern, in the final member of the application of the program Bat.java is an example of the invariant mode. If you are interested in this, you can refer to the "Java and Schema" book written by Dr. Shanhong.



So far, the use of This,static,supert and final has been finished, and if you have been able to roughly tell the difference and usage of these four keywords, then you have basically mastered it. However, anything in the world is not perfect, Java provides these four keywords, the programmer's programming has brought great convenience, but not to let you use everywhere, once the abuse of the procedure, it is counterproductive, so in use please be sure to seriously consider.








Related Article

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.