Java several key words

Source: Internet
Author: User
Tags inheritance

This article is intended to help you prepare to learn about Java and the use of the static, this, super, final, and other keywords used by friends who are just in touch with Java. Java is profound, I am also a learning and use of Java enthusiasts, the text is inevitably inappropriate, please correct me.
First, static
Please look at the following procedure first:
public class hello{
???? public static void Main (string[] args) {//(1)
????????? System.out.println ("hello,world!"); /(2)
??????? }
? }
See this procedure, for most of the learning of Java from, is not unfamiliar. Even if you have not learned Java and learned other high-level languages, such as C, you should also be able to understand the meaning of this code. It simply outputs "Hello,world" and is not useful at all, however, it shows the main use of the static keyword.
At 1, we define a static method named Main, which means to tell the Java compiler that I don't need to create an object of this class to use. Do you still have to how do you run the program? In general, we are all under the command line, enter the following command (underlined as manual input):
Javac Hello.java
Java Hello
hello,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 Hello.class file, that is the first line generated Java binary bytecode. The second line is the most common practice of executing a Java program. Execute the results as you expected. In 2, you might wonder why this is going to output. OK, let's break down this statement. (If you do not have a Java document installed, visit the 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 will find that there is a line: public static final PrintStream out; Then in the further, click on the PrintStream this hyperlink, on the method page, you will see a lot of defined methods to find println, there will be such a line:
public void println (String x). Well, now you should understand why we call that, out is a static variable of system, so it can be used directly, and the class with out belongs to a println method.
Static methods
In general, defining a method in a class is static, which means that you do not need an object of this class to call this method. As shown below:
Class simple{
?? static void Go () {
??????? System.out.println ("Go ...");
??? }
}
public class cal{
? public static void Main (string[] args) {
???? Simple.go ();
? }
}
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:
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 prove that they share a piece of storage. The 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=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 touch Java for the first time, the results may surprise you. It may be confusing to add parentheses after static. The first thing to tell you is that the variables defined by static take precedence over any other non-static variables, regardless of the order in which they appear. As 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. followed by a piece of code behind static{, which 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 to understand the static keyword. When it comes to inheritance, the static variables of the parent class are initialized first, then the subclasses, and so on. Non-static variables are not the subject of this article and are not discussed in detail here, please refer to think in Java.
Static class
Usually a normal class is not allowed to be declared static, only one inner class can. In this case, the static inner class can be used directly as a normal class, without the need to instantiate 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 have expected:
Innercls
Same as the normal class. For other uses of the inner class, see the section think in Java, which is not explained here.
Second, this & super
??? In the previous my book, we discussed the various uses of static, by defining methods or members with static, to provide some convenience for our programming, and to some extent it resembles global functions and global variables in C. But it's not that you can use it anywhere, and if you do, you need to think about whether you're programming with object-oriented thinking and whether your program is object-oriented. Okay, now we're going to talk about 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 for this purpose, and, of course, another use of this is to invoke another constructor of the current object, which will be discussed immediately. If you want to quote something from the parent class, it's not super. Since this and the super have so many similar traits and innate relationships, we're here to discuss it, hoping to help you differentiate and master two of them.
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, so you need to explicitly use the This keyword to indicate that you want to use a member, using the "this. Member name" instead of the one that is the formal parameter. In addition, you can use the "this. Method name" to refer to a method of the current object, but this is not necessary, you can directly use the method name to access the method, the compiler will know that you want to call the one. The following code demonstrates the use of the above:
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 that's not necessary.
??? Setage (age);
??? This.print ();
? }??
? public void SetName (String name) {
??? this.name=name;//must indicate here that you want to refer to the member variable
? }
? public void Setage (int.) {
??? This.age=age;
? }
? public void print () {
??? System.out.println ("name=" +name+ "age=" +age);//This is not required in this line, because there is nothing that can cause confusion
? }
? public static void Main (string[] args) {
??? Demothis dt=new demothis ("Kevin", "22");
? }
}
This code is very simple and you should be able to understand it without explaining it. In the constructor you see Using This.print (), you can completely replace it with print (), which works the same way. 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 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:
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 ();? Calling the parent class constructor (1)
??? PRT ("A Chinese."); /(4)
? }
? Chinese (String name) {
??? Super (name);//The constructor that invokes the parent class with the same parameters (2)
??? PRT ("His name is:" +name);
? }
? Chinese (String Name,int age) {
??? This (name);//Call the constructor that currently has the same formal parameter (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 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.
Third, final
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:
Import java.util.List;
Import java.util.ArrayList;
Import java.util.LinkedList;
public class bat{
??? Final pi=3.14;????????? Address value when defined
??? final int i;??????????? Because you want to initialize in the constructor, you can't give the value 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) {
??????? 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 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 the basic type of variable, this does not make any sense, because a variable of the basic type is passed when the method is called, that is, you can change the parameter variable in the method without affecting the calling statement, but it is very useful for the object variable. , because an object variable is passed its reference when it is passed, so that 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 an argument in the method, explicitly using final to declare it 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 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{
????? 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 can be seen from the program, the final class is almost no different from the use of the normal class, except that it loses the inherited attribute. The difference between final and non-final methods is difficult to see from the program line, just remember to use caution.
Application of final in design mode
There is a pattern in design mode called invariant mode, which can be easily implemented in Java with the final keyword, and the program Bat.java used to explain the final member is an example of the invariant pattern. If you're interested, you can refer to the book "Java and Patterns" written by Dr. Shanhong.
?

Java several key words

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.