Java know how many static keywords and Java static variables and static methods

Source: Internet
Author: User
Tags control characters pow

The static modifier can be used with variables and methods, which means "static".

Static variables and static methods can be accessed through the class name and do not need to create a class object to access the static members of the class, so the static decorated members are also known as class variables and class methods. Static variables are different from instance variables, and instance variables are always accessed through objects because their values differ between objects and objects.

Take a look at the following example:
1  Public classDemo {2     Static inti = 10;3     intJ;4 Demo () {5          This. J = 20;6     }7      Public Static voidMain (string[] args) {8SYSTEM.OUT.PRINTLN ("Class variable i=" +demo.i);9Demo obj =NewDemo ();TenSYSTEM.OUT.PRINTLN ("instance variable j=" +OBJ.J); One     } A}

Operation Result:

Class variable i=10
Instance variable j=20
Static variables that are statically memory-allocated are classes that do not belong to any independent object, so you can access static variables without creating an instance of the class. The result is that the compiler creates only one copy of the static variable for the entire class, that is, allocating only one memory space, although there are multiple instances, the instances share the memory. Instance variables are different, each time an object is created, the memory space is allocated once, the memory of different variables is independent from each other, and changing the instance variable of a object does not affect the B object.

Take a look at the following code:
1  Public classDemo {2     Static inti;3     intJ;4      Public Static voidMain (string[] args) {5Demo obj1 =NewDemo ();6OBJ1.I = 10;7OBJ1.J = 20;8        9Demo Obj2 =NewDemo ();Ten         OneSystem.out.println ("obj1.i=" + obj1.i + ", obj1.j=" +OBJ1.J); ASystem.out.println ("obj2.i=" + obj2.i + ", obj2.j=" +obj2.j); -     } -}

Operation Result:

obj1.i=10, obj1.j=20
obj2.i=10, obj2.j=0

Note: Although static variables can also be accessed through objects, they are not advocated and the compiler generates warnings.

In the above code, I is a static variable, change the value of I by OBJ1, will affect the obj2;j is an instance variable, by obj1 change the value of J, will not affect the obj2. This is because obj1.i and obj2.i point to the same memory space, and OBJ1.J and OBJ2.J point to different memory spaces, see:
Figure 1 Static variable memory allocation
Note: Static variables are initialized when the class is loaded. That is, whenever a class is loaded, it will be initialized whether or not you use the static variable.

Summary: Class variables is modified with the keyword static, when the class is loaded, allocates the memory of the class variable, and later generates the class's instance object, the memory (class variable) will be shared, and any modification of the class variable by any object will affect other objects. There are two external access methods: Access by object or by class name. Static methods A static method is a method that cannot be manipulated to an object. For example, the POW () method of the Math class is a static method with the syntax of Math.pow (x, a), which computes the power of a in X, without creating any Math objects.

Because static methods cannot manipulate objects, instance variables cannot be accessed in static methods, only static variables of their own classes can be accessed.

Static methods can be used in the following situations:
    • A method does not require access to the object state, and its required parameters are provided by explicit arguments (for example, Math.pow ()).
    • A method only needs to access the static variables of the class.

The reader must note that main () is also a static method and does not operate on any object. In fact, there are no objects at the start of the program, and the main () method is the entry for the program, which is executed and the object required by the program is created.

A summary of static variables and static methods:
    • A static method of a class can only access static variables;
    • A static method of a class is not able to invoke a non-static method directly;
    • Static variables and static methods can also be accessed through objects, but not recommended, as access control permissions allow;
    • The current object does not exist in the static method and therefore cannot be used, nor can the super be used, of course;
    • Static methods cannot be overridden by non-static methods;
    • The construction method does not allow the declaration to be static;
    • Local variables cannot use static adornments.

Examples of static methods:
1  Public classDemo {2     Static intSumintXinty) {3         returnX +y;4     }5      Public Static voidMain (string[] args) {6         intsum = Demo.sum (10, 10);7System.out.println ("10+10=" +sum);8     }9}

Operation Result:

10+10=20

The static method does not require any instances of the class it belongs to be called, so there is no this value and the instance variable cannot be accessed, otherwise it will cause a compilation error.

Note: Instance variables can only be accessed through objects and cannot be accessed through a class.
Static initializers (static block) blocks are a piece of code surrounded by curly braces. Static Initializer is a static block that exists in the class, outside of the method. Static initializers are only executed once when the class is loaded (the first time the class is used) and are often used to initialize static variables.

Example code:
1  Public classDemo {2      Public Static inti;3     Static{4i = 10;5System.out.println ("Now in Static block."));6     }7      Public voidTest () {8System.out.println ("Test method:i=" +i);9     }Ten      Public Static voidMain (string[] args) { OneSystem.out.println ("demo.i=" +demo.i); A         NewDemo (). Test (); -     } -}

The operating result is:

Now in static block.
demo.i=10
Test method:i=10
Static import static import is a new feature of Java 5 that imports static variables and static methods for classes.

In general, we import classes that write:
1 Import // to import a particular class

Or

1 Import // Import all classes in a package

Static imports can be written like this:

1 Import Static // to import a specific static method

Or

1 Import Static // Import all static members in a class

After importing, you can call a static method directly in the current class using the method name without having to use classname.methodname to access it.


For static variables and static methods that are used frequently, you can import them statically. The advantage of a static import is that it simplifies some operations, such as the output statement System.out.println (); The out in is the static variable of the System class, which can be java.lang.system.* by the import static; Import it, and the next time you call Out.println ().

Take a look at the following code:
1 Import Staticjava.lang.system.*;2 Import StaticJava.lang.Math.random;3  Public classDemo {4      Public Static voidMain (string[] args) {5Out.println ("generated by a random number:" +random ());6     }7}

Operation Result:

A random number generated: 0.05800891549018705

Series Articles:

Java know how much (1) Language overview

Java know how much (2) virtual machine (JVM) and cross-platform principle

Java know how much (3) employment direction

Java know how much (4) the difference between J2SE, Java EE, J2ME

Java know how much (5) Build Java development environment

Java know how much (6) The first example of a program

Java knows how many (7) classes and objects

Java know how much (8) class library and its organizational structure

Java know how much (9) Import and Java class search path

Java know how much (10) data types and variables

Java know how much (11) data type conversions

Java know how many (12) operators

Java know how much (13) Process Control

Java know how many (14) arrays

Java know how much (15) string

Java know how much (StringBuffer) and Stringbuider

Java know how much (17) emphasize the programming style

Java know how many (18) classes are defined and instantiated

Java know how many (19) access modifiers (access control characters)

Java knows how many (20) variables are scoped

Java know how much (+) This keyword is detailed

Java know how many (22) method overloads

Java know how much (23) the basic run order of classes

Java know how much (24) packaging class, unpacking and packing detailed

Java know how much (25) More about Java package

Java know how much (26) claim rules for source files

Java know how much (27) the concept and implementation of inheritance

Java know how many super keywords

Java know how much (29) Overwrite and reload

Java know how much (30) polymorphic and dynamic binding

Java know how many static keywords and Java static variables and static methods

Java know how many static keywords and Java static variables and static methods

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.