Static keyword in Java comprehensive parsing _java

Source: Internet
Author: User

Static keyword is a lot of friends in the code and read the code when the more difficult to understand a keyword, but also the major companies in the interviewer like to ask in the interview one of the knowledge points. The following is the first to describe the use of the static keyword and the usual easy to misunderstand the place, and finally listed some of the interview written in the common static questions. The following is a table of contents outline for this article:

I. Purpose of the STATIC keyword

Two. Error of the static key word

Three. Common written test face questions

If there is any difference, I hope to understand and welcome criticism.

Please respect the results of the work of the author, reproduced please indicate the original link:

Http://www.cnblogs.com/dolphin0520/p/3799052.html

I. Purpose of the STATIC keyword

"The static method is a method without this. Non-static methods cannot be invoked inside the static method, which in turn is possible. And you can invoke the static method simply by using the class itself without creating any objects. This is actually the main purpose of the static method. ”

While this statement only illustrates the special point of the static method, it is possible to see the basic role of the static keyword, in short, a sentence to describe:

Easy to invoke (method/variable) without creating an object.

Obviously, a method or variable modified by the static keyword does not need to depend on the object for access, so long as the class is loaded, it can be accessed through the class name.

Static can be used to modify the member methods of a class, the member variables of a class, and a static code block to optimize program performance.

1) static method

Static methods are generally referred to as static methods, and because static methods can be accessed without relying on any object, there is no this for static methods because it is not attached to any object and since there is no object, this is not the case. And because of this feature, non-static member variables and non-static member methods of a class cannot be accessed in a static method, because Non-static member methods/variables must depend on specific objects to be invoked.

Note, though, that non-static member methods and non-static member variables cannot be accessed in static methods, but static member methods/variables can be accessed in Non-static member methods. For a simple example:

In the code above, because the Print2 method is independent of the object, it can be invoked directly with the class name. If you can access a Non-static method/variable in a static method, if you have the following statement in the Main method:

Myobject.print2 ();

At this time the object is not, STR2 does not exist at all, so it will create contradictions. The same is true for methods, because you cannot predict whether a non-static member variable is accessed in the Print1 method, so it is also prohibited to access non-static member methods in static member methods.

For Non-static member methods, it is obviously unrestricted to access static member methods/variables.

Therefore, if you want to invoke a method without creating an object, you can set this method to static. Our most common static method is the main method, and it is now clear why the main method must be static. Because the program does not create any objects when it executes the main method, it is accessible only through the class name.

Also remember that the constructor of a class is actually a static method, even if it is not shown as static.

2) Static variable

Static variables are also referred to as static variables, and the difference between statics and non-static variables is that static variables are shared by all objects and only one copy in memory, which is initialized only when the class is first loaded. Non-static variables, which are owned by objects, are initialized when objects are created, multiple replicas exist, and replicas owned by each object do not affect each other.

The initialization order of the static member variables is initialized in the order defined.

3) Static code block

The static keyword also has a more critical role to play in creating static blocks of code to optimize program performance. A static block can be placed anywhere in a class, and there can be more than one static block in a class. When the class is first loaded, each static block is executed in the order of the static block and is executed only once.

Why the static block can be used to optimize program performance is because of its characteristics: it only executes once when the class is loaded. Let's look at an example:

Class person{
private Date birthdate;
Public person (Date birthdate) {
this.birthdate = birthdate;
}
Boolean Isbornboomer () {
Date startdate = date.valueof ("1946");
Date EndDate = date.valueof ("1964");
Return Birthdate.compareto (startdate) >=0 && Birthdate.compareto (EndDate) < 0;
}

Isbornboomer is used to see if this person was born in 1946-1964, and every time Isbornboomer is called, StartDate and birthdate two objects are generated, creating a waste of space, which would be better if it were changed:

Class person{
private Date birthdate;
private static Date startdate,enddate;
static{
startdate = date.valueof ("1946");
EndDate = date.valueof ("1964");
}
Public person (Date birthdate) {
this.birthdate = birthdate;
}
Boolean Isbornboomer () {return
Birthdate.compareto (startdate) >=0 && Birthdate.compareto (enddate) < 0;
}

As a result, a number of initialization operations that need to be performed only once are placed in a static code block.

Two. Error of the static key word

Does the 1.static keyword change the access rights of members in a class?

Some novice friends confuse the static in Java with the functionality of the static keyword in C + +. Only one thing to remember here is that the static keyword in Java does not affect the scope of a variable or method, unlike static in C + +. The only few keywords that can affect access in Java are private, public, protected (including package access). Take a look at the example below to see:

The prompt error "Person.age" indicates that the static keyword does not change the access rights of variables and methods.

2. Can I access static member variables through this?

Although there is no this for static methods, can you access static member variables through this in Non-static methods? Let's look at one of the following examples, what is the output of this piece of code?

public class Main {
static int value =; 
public static void Main (string[] args) throws exception{
new Main (). Printvalue ();
private void Printvalue () {
int value = 3;
System.out.println (This.value);
}

33

This is the main expedition to this and static understanding. What does this represent? This represents the current object, and the current object is the object generated by new main () by invoking Printvalue with new Main (). While the static variable is enjoyed by the object, the value of the This.value in Printvalue is no doubt 33. The value inside the Printvalue method is a local variable and it is impossible to associate with this, so the output is 33. Always remember that static member variables, while independent of objects, do not mean that they cannot be accessed through objects, and all static methods and static variables can be accessed through objects (as long as access is sufficient).

Can 3.static work on local variables?

Static is scoped to local variables in C + +, but remember in Java: Static is not allowed to modify local variables. Don't ask why, this is a rule of Java syntax.

Three. Common written test face questions

Here are some of the interview written on the Static keyword frequently encountered in the topic, for reference only, if there is a further welcome to the comments below.

1. What is the output of the following code?

public class Test extends base{
static{
System.out.println ("Test static");
}
Public test () {
System.out.println ("Test constructor");
}
public static void Main (string[] args) {
new Test ();
}
}
Class base{
static{
System.out.println ("Base static");
}
Public Base () {
System.out.println ("Base constructor");
}

Base static
Test static
Base constructor
Test constructor

As for why this is the result, let's not discuss it first and think about the specific execution of this code, and start by looking for the main method, because the main method is the entrance to the program, but before you execute the main method, you must load the test class. When the test class is loaded, it is found that the test class inherits from the base class, so the base class is loaded and the static block is executed when the base class is loaded and a static block is found. After the base class load completes, the test class continues to load, and then the static block is executed when the test class is also found with static blocks. After the required class has been loaded, the main method is executed. When you execute the new Test () in the main method, the constructor of the parent class is invoked, and then its own constructor is called. As a result, the above output is present.

2. What is the output of this code?

The public class Test {person person
= new Person ("test");
static{
System.out.println ("Test Static");
}
Public test () {
System.out.println ("Test constructor");
}
public static void Main (string[] args) {
new MyClass ();
}
}
Class person{
static{
System.out.println ("person static");
}
Public person (String str) {
System.out.println (' person ' +str);
}
Class MyClass extends Test {person person
= new Person ("MyClass");
static{
System.out.println ("MyClass Static");
}
Public MyClass () {
System.out.println ("MyClass constructor");
}

Test static 1
Test static 2

Although there is no statement in the main method, it is still output, as explained above. In addition, the static block can appear anywhere in the class (as long as it is not inside of the method, remember, not within any method), and execution is performed in the order of the static block.

The above is a small set to introduce the Java Static keyword comprehensive analysis, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.