Java basics-Use of static keywords, java-static keywords

Source: Internet
Author: User

Java basics-Use of static keywords, java-static keywords

I. Functions of static keywords

Make the class members completely independent from any objects of the class. Generally, a class member must be accessed through its class object, but the static modified member can be accessed by itself without referencing a specific instance.

Once a member is declared as static, it can be accessed before any object of its class is created without referencing any object.

A variable declared as static is essentially a global variable. when an object is declared, it is not a copy of The stitc variable, but a static variable shared by all instance variables of this class.

Methods declared as static have the following restrictions:

1. They can only call other static methods;

2. They can only access static data;

3. They cannot reference this and super in any form

If you need to initialize your static variable through calculation, you can declare a static block, which is only executed once when the class is loaded.

The following example shows that the class has a static method, some static variables, and a static initialization block:

// Demonstrate static variables,methods,and blocks.class UseStatic { static int a = 3; static int b; static void meth(int x) {System.out.println("x = " + x);System.out.println("a = " + a);System.out.println("b = " + b); } static {System.out.println("Static block initialized.");b = a * 4; } public static void main(String args[]) {meth(42); }}

Once the UseStatic class is loaded, all static statements are run. First, a is set to 3, then static block execution (print a message), and finally B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to x. The three println () Statements reference two static variables a and B, and the local variable x.

Call static member variables

Class Name. static modified Member

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.