Java notes 17. Static and final usage in Java

Source: Internet
Author: User

in the last few posts we know that when we write a class, we are actually describing the properties and behavior of the class object, and there is no real object, only the new keyword will produce the object, then the system will allocate memory space to the object, its method can be called externally. But sometimes, we want the static keyword to be useful, regardless of whether or not an object has been produced or how many objects have been generated, and some specific data is only in memory space.
first, the static keyword
1. Static member variables/methodswhen you add a static keyword to a class member (variable/method) , the member is called a static member variable/method. a static variable is somewhat similar to a global variable in another language , and if the static member variable is not private, it can be accessed outside the class without the need to produce an instance object of the class, and only the class name (the class name, static member) can be referenced. usage of 2.static keywordsvariables decorated with the static identifier, which are created when the class is loaded, and as long as the class exists, the static variable exists. Because static member variables can be shared by each instance object , we can use him to achieve some special effects. (1) Static code blockform: static{...}a static block of code that is not contained in any method body can be used in a class, when the class is loaded, the static code block is executed, and only executed sequentially, so static blocks are often used for initialization of class properties. Source: Teststatic.java
<span style= "FONT-SIZE:18PX;" >class Staticcode {static String school; static{  school= "University City University";//static member variable assignment  System.out.println ("I am Staticcode "); }}public class Teststatic {static {  System.out.println ("Teststatic is loading ...");} public static void Main (string[] args) {  System.out.println ("in the main thread");  New Staticcode ();  New Staticcode (); }}</span>
Printing information:
Analysis: We can draw the following conclusions when we look at the information printed by the program. A. Static code blocks in class Staticcode are automatically executed, although the static code blocks of the class are executed only once , despite the two instance objects that produced the Staticcode of the classes Static blocks of code in the class are executed only when the class is used; B. The class is loaded when it is first used, not all classes that might be used in the program when the program starts.
(2) Single-state class designFirst, we understand the next class of the single-state design pattern, that is, to take certain methods to ensure that in the entire software system, a class can only have one object instance, and the class only provides a method to obtain its object instance. //single-state classclass TestSingle {Private TestSingle () {}//privately constructed methodPrivate final static testsingle single = new TestSingle ();//construct TestSingle a private instance objectPublic static TestSingle getsingleinstance ()//Return the private object     {return single;      }}then we can go through the testsingle in the main thread. The getsingleinstance () method to get the unique object of the single class. Source: Staticdemo.java
<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >//Single class TestSingle {private TestSingle () {}//Private constructor method privately final static testsingle a = new TestSingle ();//Construction TestSingle a private instance object public static TestSingle getsingleinstance ()//returns the private object {  return single,} public void print () {
   
    system.out.println ("I am TestSingle class"); }}//main class public class staticdemo{public static void Main (string[] args) {  System.out.println ("in Main thread");  TestSingle single=testsingle.getsingleinstance (); Create  a single.print ();//Invoke public method}}</span></span> in a single-state class
   

Printing information:
Analysis: If you want a class to intelligently produce an object in a virtual machine, we can use static to design a single-state classA. First, you must set the access permission of the class's constructor to private so that you can produce the object of the class outside of the class with the new operator, and of course we can still produce objects of that class within the class. B. Use the new operator in a singleton class to produce an instance object that is statically private and can only be used by static methods of this classC. Since we cannot get the object of that single class outside of the class, all of us implement a static method in a single class to return the internally created object. It is important to note that static methods can only access static member variables in the class. 3. Considerations for using the Static keyword(1) in a static method, only other static members (including variables and methods) in the same class can be called directly, and non-static members in the classes cannot be accessed directly . Because for non-static methods and variables, you need to create an instance object of the class before you can use it, and the static method does not have to create any objects before it is used. (2) The static method cannot refer to the this and the Super keyword in any way . Because static methods do not have to create any instance objects before they are used, the object referenced by this is not produced at all when the static method is invoked. (3) themain () method is static, and the hidden JVM does not create an instance object of the same class as the main method when it executes the main method . Thus, in the main () method, you cannot access non-static members of the class directly, and you must create an instance object of the class to access non-static members of the class through this object .
Second, final keywords
when we write Java code, we often see that when we declare classes, properties, and methods in Java, we use the keyword final to decorate. Now let's learn what the final keyword really does. 1.final Tagged classes cannot be inherited;2.final Marking method can not be overridden by the quilt class;A 3.final tagged variable, whether a member variable or a local variable, becomes a constant and can only be assigned once . In addition, the member variables of the final tag must be declared at the same time or displayed in the constructor method of the class to be used. class Test{final int x=3;}or:class Test{final int x;Test ()    {x=3;    }}Note:(1) A variable of the final tag (a member or a local variable) becomes a constant and can be assigned only sequentially, but the "constant" can only be used internally within the class and cannot be used directly outside the class . (2) defining constants in Java, usually using public static final to mark the constant, then the constant is the global constant . However, constants of this definition can only be assigned when defined, even if they are not assigned to a constructor.

Java notes 17. Static and final usage in Java

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.