Home>Article>Java> What is static in java? How to understand?

What is static in java? How to understand?

王林
王林 Original
2019-11-12 16:34:09 5727browse

What is static in java? How to understand?

In the Java language, static means "static". The usage scenario can be used to modify member variables and member methods, and of course it can also be a static code block. The main function of static is to create domain variables or methods that are independent of specific objects.

Format:

Modified variable: static data type variable name

Modified method: [Access permission modifier] static method return value method name ( Parameter list)

Features:

1. Static can modify variables and methods;

2. Variables or methods modified by static are independent of Any object of this class, that is to say, these variables and methods do not belong to any instance object, but are shared by instance objects of the class;

3. When the class is loaded, it will be loaded The part modified by static;

4. Variables or methods modified by static take precedence over objects, which means that after a class is loaded, it can be accessed even if no object is created.

The difference between static variables and instance variables:

Instance variables: Every time an object is created, member variable memory space is allocated for each object. Instance variables belong to the instance For objects, in memory, as many times as the object is created, there will be several member variables.

Static variables: Static variables do not belong to any instance object but belong to the class, so there will only be one copy in the memory. During the loading process of the class, the JVM allocates memory space once for the static variables.

Application scenario:

If a member variable is shared by all objects, then this member variable should be defined as a static variable.

Notes:

1. There is no this keyword in the static method, because static is loaded with the loading of the class, and this is loaded with the object. Created to exist. Static objects take precedence over objects.

2. Static can access static, but static cannot access non-static.

3. Non-static ones can access static ones.

Recommended tutorial:Java tutorial

The above is the detailed content of What is static in java? How to understand?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn