Static keyword parsing in Java and javastatic keyword

Source: Internet
Author: User

Static keyword parsing in Java and javastatic keyword

The static keyword is a hard-to-understand keyword that many friends encounter when writing and reading Code. It is also one of the key points that the interviewers of major companies like to ask during the interview. The following describes the usage of static keywords and common misunderstandings. Finally, it lists some common static questions in the interview test. The following is the directory outline of this article:

I. usage of the static keyword

Ii. misunderstandings of static keywords

Iii. Common examination questions

If any, I hope to understand and welcome criticism.

I. usage of the static keyword

On the P86 page of Java programming ideology, there is a passage like this:

"The static method does not have this method. Non-static methods cannot be called within the static method, which is the opposite. In addition, the static method can be called only by the class itself without creating any object. This is actually the main purpose of the static method ."

Although this section only describes the special characteristics of the static method, we can see the basic function of the static keyword. In short, the following is a description:

It is convenient to call (methods/variables) without creating an object ).

Obviously, methods or variables modified by the static keyword do not need to be accessed by objects. As long as the class is loaded, the class name can be used for access.

Static can be used to modify the member methods and member variables of a class. In addition, you can write static code blocks to optimize program performance.

1) static Method

A static method is generally called a static method. Because a static method can be accessed without any object, it does not have this for a static method because it is not attached to any object, since there are no objects, we can't talk about this. Due to this feature, non-static member variables and non-static member methods of the class cannot be called in static methods, because non-static member methods/variables must depend on specific objects to be called.

However, although non-static member methods and non-static member variables cannot be accessed in static methods, static member methods and variables can be accessed in non-static member methods. A simple example:

In the above Code, the print2 method is independent of the object, and can be called directly by class name. If you can access non-static methods/variables in static methods, the following statement is provided in the main method:

MyObject. print2 ();

In this case, no object exists, and str2 does not exist at all, so there is a conflict. The same is true for methods. Since you cannot predict whether non-static member variables are accessed in the print1 method, access to non-static member methods is also prohibited.

For non-static member methods, it is obviously unlimited to access static member methods/variables.

Therefore, if you want to call a method without creating an object, you can set this method to static. The most common static method is the main method. As to why the main method must be static, it is clear now. Because no object is created when the program executes the main method, it can only be accessed through the class name.

In addition, remember that even if the ground definition is not displayed as static, the class constructor is actually a static method.

2) static variables

Static variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects and have only one copy in the memory, it is initialized only when the class is first loaded. Non-static variables are owned by objects. They are initialized when an object is created and have multiple copies. The copies of each object do not affect each other.

Static member variables are initialized in the defined order.

3) static code block

The static keyword also plays a key role in forming static code blocks to optimize program performance. The static block can be placed anywhere in the class, and there can be multiple static blocks in the class. When the class is loaded for the first time, each static block is executed in the order of static blocks, and only once.

Why is it that static blocks can be used to optimize program performance? They are only executed once during class loading. The following is 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 determine whether the person was born in 1946-1964 years. Every time isBornBoomer is called, The startDate and birthDate objects are generated, resulting in a waste of space:

 

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;

}

}

Therefore, some initialization operations that only need to be performed once are put in the static code block.

Ii. misunderstandings of static keywords

1. Will the static keyword change the access permissions of members in the class?

Some beginners will confuse static in java with the function of static keywords in C/C ++. Note: Unlike static in C/C ++, static keywords in Java do not affect the scope of variables or methods. In Java, only the keywords private, public, and protected (including package access permissions) can be affected. You can see the following example:

The error "Person. age is not visible" indicates that the static keyword does not change the access permissions of variables and methods.

2. can I access static member variables through this?

Although this is not available for static methods, can static member variables be accessed through this in non-static methods? Let's take a look at the following example. What is the output of this code?

 

Public class Main {

Static int value = 33;

 

Public static void main (String [] args) throws Exception {

New Main (). printValue ();

}

 

Private void printValue (){

Int value = 3;

System. out. println (this. value );

}

}

 

33

This section mainly describes the understanding of this and static. What does this mean? This indicates the current object. If printValue is called through new Main (), the current object is an object generated through new Main. Static variables are enjoyed by objects, so the value of this. value in printValue is undoubtedly 33. The value in the printValue method is a local variable and cannot be associated with this at all. Therefore, the output result is 33. Remember that static member variables are independent of objects, but do not mean they cannot be accessed through objects, all static methods and static variables can be accessed through objects (as long as the access permission is sufficient ).

3. Can static be applied to local variables?

In C/C ++, static can be used to modify local variables. However, in Java, static cannot be used to modify local variables. Don't ask why. This is the Java syntax.

Iii. Common examination questions

The following lists some questions about the static keyword that are frequently encountered during the interview test. They are for reference only. If you have any questions, please leave a message below.

1. What is the output result 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 to why this result is, let's not discuss it first. Let's first look at the specific execution process of this Code. At the beginning of execution, we need to find the main method, because the main method is the entry of the program, however, before executing the main method, you must first load the Test class. when loading the Test class, you find that the Test class inherits from the Base class. Therefore, the Test class is transferred to the Base class first, when the Base class is loaded, a static block is executed when a static block is found. After the Base class is loaded, continue to load the Test class, and find that there are static blocks in the Test class, and then execute the static block. After the required classes are loaded, the main method is executed. When new Test () is executed in the main method, the constructor of the parent class is called first, and then its constructor is called. Therefore, the above output result is displayed.

2. What is the output result of this code?

 

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

Myclass static

Person static

Person Test

Test constructor

Person MyClass

Myclass constructor

Similarly, let's take a look at the specific execution process of this Code. Load the Test class first, so the static block in the Test class will be executed. Then execute new MyClass (), and The MyClass class has not been loaded, so the MyClass class needs to be loaded. When loading the MyClass class, I found that the MyClass class inherits from the Test class. However, because the Test class has been loaded, I only need to load the MyClass class, then the static block in the MyClass class will be executed. After loading, an object is generated through the constructor. When an object is generated, the member variable of the parent class must be initialized first, so the Person person = new Person () in Test will be executed, and the Person class has not been loaded yet, therefore, the system first loads the Person class and executes the static block in the Person class, then executes the constructor of the parent class, completes the initialization of the parent class, and then initializes itself, therefore, the Person person = new Person () in MyClass will be executed, and the MyClass constructor will be executed.

3. What is the output result of this code?

 

Public class Test {

Static {

System. out. println ("test static 1 ");

}

Public static void main (String [] args ){

}

Static {

System. out. println ("test static 2 ");

}

}

 

test static 1
test static 2

Although there are no statements in the main method, it will still be output because it has been described above. In addition, the static block can appear anywhere in the class (as long as it is not inside the method, remember, it cannot be inside any method), and the execution is performed in the order of the static block.

Head of Java

No.: javatuanzhang

Sharing Java technical expertise on a daily basis

Long-pressed QR code recognition

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.