Introduction to Java first season _1.8_static keywords

Source: Internet
Author: User

The Static keyword in Java

The static keyword is often a must-ask point for an interview, so it's a separate introduction.
This article refers to the blog from Haizi
The content of the original text has been adjusted.

A. Static use

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

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

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

1.static method

Static methods are commonly referred to as static methods, and because they 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 are no objects, this is not the case. And because of this feature, non-static member variables and non-static member methods of the class cannot be accessed in a static method, because non-static member methods/variables must be dependent on a specific object to be able to be called.

It is important to note, though, that non-static member methods and non-static member variables cannot be accessed in static methods, but static member methods/variables are accessible in non-static member methods. To give a simple example:

In the above code, because the Print2 method is independent of the object, it can be called directly with the class name. If you can access a non-static method/variable in a static method, then 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 there will be contradictions. The same is true for methods, because you cannot predict whether non-static member variables are accessed in the Print1 method, and you also prohibit access to non-static member methods in static member methods.

For non-static member methods, it is clear that there is no limit to accessing static member methods/variables.

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

2.static variables

Static variables are also known as static variables, except that the static variables are shared by all objects, only one copy in memory, and are initialized only when the class is first loaded. Instead of static variables, which are owned by an object, are initialized when the object is created, there are multiple copies, and the replicas owned by each object do not affect each other.

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

3.static code block

Another key function of the static keyword is to form static blocks of code to optimize program performance. A static block can be placed anywhere in the class and can have more than one static block in the class. When the class is first loaded, each static block is executed in the order of the static blocks and is executed only once.

 Public  class HelloWorld {String name;//Declare variable nameString sex;//DECLARE variable sex    Static intAge//Declare static variable age    //Construction method     Public  HelloWorld() {System.out.println ("Initialize name by construction method"); Name ="Tom"; }//Initialization block{System.out.println ("Initialize sex by initializing blocks "); Sex ="Male"; }//Static initialization block      Static{System.out.println ("Initialize age by static initialization block"); Age = -; } Public void Show() {System.out.println ("Name:"+ name +", Gender:"+ Sex +", Age:"+ age); } Public Static void Main(string[] args) {//Create ObjectsHelloWorld Hello =NewHelloWorld ();//Call the object's Show methodHello.show (); }}

Execution results
Initializing the age with static initialization blocks
Initialize the sex by initializing the Block
Initialize name by constructing method
Name: Tom, Sex: Male, Age: 20

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

class Person{    private Date birthDate;    publicPerson(Date birthDate) {        this.birthDate = birthDate;    }    boolean isBornBoomer() {        Date startDate = Date.valueOf("1946");        Date endDate = Date.valueOf("1964");        return birthDate.compareTo(startDate)>=00;    

Isbornboomer is used for this person is born 1946-1964, and each time Isbornboomer is called, will generate StartDate and birthdate two objects, resulting in space waste, if changed to such efficiency will be better:

class Person{    private Date birthDate;    privatestatic Date startDate,endDate;    static{        startDate = Date.valueOf("1946");        endDate = Date.valueOf("1964");    }    publicPerson(Date birthDate) {        this.birthDate = birthDate;    }    boolean isBornBoomer() {        return birthDate.compareTo(startDate)>=00;    

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

Two. The myth of the Static keyword does the 1.static keyword change the access rights of members in a class?

* The static keyword in Java does not affect the scope of a variable or method. * the only private, public, protected (including package access) keywords that can affect access in Java. See the following example to understand:

The error "Person.age is not seen" indicates that the STATIC keyword does not alter the access rights of variables and methods.

2. Can I access static member variables through this?

Although there is no this for static methods, is it possible to access static member variables through this in a non-static method? Let's look at one of the following examples, what is the result of this code output?

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); }} 

Execution results
33
This is the understanding of the main expedition this and the static. What does this represent? This represents the current object, so the current object is the object generated through new main () by calling Printvalue with new Main (). The static variable is enjoyed by the object, so the value of This.value in Printvalue is undoubtedly 33. The value inside the Printvalue method is a local variable and cannot be associated with this at all, so the output is 33. Always keep in mind that static member variables, while independent of the object, do not mean that they cannot be accessed through objects, and that all static and static variables can be accessed through the object (as long as access is sufficient).

Can 3.static act on local variables?

In Java, remember that static is not allowed to decorate local variables. Do not ask why, this is the Java syntax of the provisions.

Three. Common written test questions 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) {NewTest (); }}class base{Static{System.out.println ("Base Static"); } Public Base() {System.out.println ("Base constructor"); }}

Execution results
Base static
Test static
Base constructor
Test constructor

-At the beginning of execution, find the main method first, because the main method is the entry of the program, but before executing the main method, the test class must be loaded, and the test class is found to inherit from the base class when the test class is loaded.
-so it's going to load the base class first, and when the base class is loaded, a static block is found and the static block is executed.
-After the base class is loaded, the test class continues to load, and then the static block is executed when the test class is found with a static block.
-After the required classes have been loaded, execute the main method.
-When you execute new Test () in the main method, the constructor of the parent class is called first, and then the constructor for itself is called.

2. What is the output of this piece of code?
 Public  class Test {Person person =NewPerson ("Test");Static{System.out.println ("Test Static"); } Public Test() {System.out.println ("Test constructor"); } Public Static void Main(string[] args) {NewMyClass (); }}class person{Static{System.out.println ("Person Static"); } Public  Person(String str) {System.out.println ("Person"+STR); }}class MyClass extends Test {person person =NewPerson ("MyClass");Static{System.out.println ("MyClass Static"); } Public MyClass() {System.out.println ("MyClass Constructor"); }}

Execution results
Test static
MyClass static
Person static
Person Test
Test constructor
Person MyClass
MyClass constructor

-The test class is loaded first, so the static blocks in the test class are executed.
-Then execute new MyClass (), and the MyClass class is not loaded, so the MyClass class needs to be loaded.
-When loading the MyClass class, it is found that the MyClass class inherits from the test class, but because the test class has already been loaded, only the MyClass class needs to be loaded, then the static blocks in the MyClass class are executed.
-After loading, the object is generated from the constructor.
-While generating the object, the member variable of the parent class must be initialized first, so the person person in test = new person () is executed, and the person class has not been loaded, so the person class is loaded first and the static block in the person class is executed.
-then executes the constructor of the parent class, completes the initialization of the parent class, and then initializes itself, then executes the person person in MyClass = new person () and finally executes the MyClass constructor.

3. What is the output of this piece of code?
publicclass Test {    static{        System.out.println("test static 1");    }    publicstaticvoidmain(String[] args) {    }    static{        System.out.println("test static 2");    

Execution results
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 the method, remember that no method is internal), and execution is performed in the order of the static blocks.

Introduction to Java first season _1.8_static keywords

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.