Home  >  Article  >  Java  >  Detailed explanation of the role and usage of static variables in Java

Detailed explanation of the role and usage of static variables in Java

伊谢尔伦
伊谢尔伦Original
2016-11-26 09:13:532046browse

static means "global" or "static" and is used to modify member variables and member methods. It can also form a static code block, but there is no concept of global variables in the Java language.

  Member variables and member methods modified by static are independent of any object of the class. That is, it does not depend on a specific instance of the class and is shared by all instances of the class.

As long as this class is loaded, the Java virtual machine can find them by default in the method area of ​​the runtime data area based on the class name. Therefore, a static object can be accessed before any of its objects are created, without referencing any objects.

Static member variables and member methods modified with public are essentially global variables and global methods. When an object of its class is declared, a copy of the static variable is not generated, but all instances of the class share the same static variable.

  A static variable can be preceded by a private modification, which means that this variable can be used in the static code block of the class, or in other static member methods of the class (of course it can also be used in non-static member methods - nonsense), but it cannot be used in other It is important to refer directly to the class through the class name. In fact, you need to understand that private means access permission restriction, and static means it can be used without instantiation, which is much easier to understand. The effect of adding other access permission keywords before static is also the same.

Static-modified member variables and member methods are customarily called static variables and static methods. They can be accessed directly through the class name. The access syntax is:

 Class name. Static method name (parameter list...)

Class name. Static variable name

A code block modified with static represents a static code block. When the Java Virtual Machine (JVM) loads a class, the code block will be executed (very useful, haha).

 1. Static variables

Class member variables can be classified into two types according to whether they are static: one is a variable modified by static, called a static variable or class variable; the other is a variable that is not modified by static, called instance variables.

 The difference between the two is:

 For static variables, there is only one copy in the memory (saving memory). The JVM only allocates memory once for static variables. The memory allocation of static variables is completed during the process of loading the class, and can be directly accessed by the class name. (convenient), of course it can also be accessed through objects (but this is not recommended).

 For instance variables, before an instance is created, memory will be allocated once for the instance variable. Instance variables can have multiple copies in the memory without affecting each other (flexible).

 So static variables are generally used when the following two functions need to be implemented:

When sharing values ​​between objects

When accessing variables is convenient

 2. Static methods

 Static methods can be called directly through the class name, any Instances can also be called,

Therefore, the this and super keywords cannot be used in static methods, and the instance variables and instance methods of the class to which they belong cannot be directly accessed (that is, member variables and member methods without static), and the class to which they belong can only be accessed. static member variables and member methods.

 Because instance members are associated with specific objects! This needs to be understood and figured out, not memorized! ! !

 Because static methods are independent of any instance, static methods must be implemented and cannot be abstract.

 For example, in order to facilitate method calling, all methods in the Math class in the Java API are static, and the static method inside a general class also facilitates other classes to call the method.

 Static method is a special type of method inside a class. The corresponding method is declared static only when needed. Methods inside a class are generally non-static

 3. Static code block

 Static code block is also It is called a static code block. It is a static statement block in a class that is independent of class members. There can be multiple and can be placed anywhere. It is not in any method body. The JVM will execute these static code blocks when loading the class. If the static code There are multiple blocks, and the JVM will execute them in the order they appear in the class. Each code block will only be executed once. For example:

public class Test5 {   
private static int a;   
private int b;   
 
static{   
Test5.a=3;   
System.out.println(a);   
Test5 t=new Test5();   
t.f();   
t.b=1000;   
System.out.println(t.b);   
}   
static{   
Test5.a=4;   
System.out.println(a);   
}   
public static void main(String[] args) {   
// TODO 自动生成方法存根   
}   
static{   
Test5.a=5;   
System.out.println(a);   
}   
public void f(){   
System.out.println("hhahhahah");   
}   
}

Running results:

3
hhahhahah
1000
4
5

You can use static code blocks to assign values ​​to some static variables. Finally, take a look at these examples. They all have a static main method, so that the JVM can call it directly when running the main method. Create an instance.

  4、static和final一块用表示什么

  static final用来修饰成员变量和成员方法,可简单理解为“全局常量”!

  对于变量,表示一旦给值就不可修改,并且通过类名可以访问。

  对于方法,表示不可覆盖,并且可以通过类名直接访问。

  有时你希望定义一个类成员,使它的使用完全独立于该类的任何对象。通常情况下,类成员必须通过它的类的对象访问,但是可以创建这样一个成员,它能够被它自己使用,而不必引用特定的实例。在成员的声明前面加上关键字static(静态的)就能创建这样的成员。如果一个成员被声明为static,它就能够在它的类的任何对象创建之前被访问,而不必引用任何对象。你可以将方法和变量都声明为static。static 成员的最常见的例子是main( ) 。因为在程序开始执行时必须调用main() ,所以它被声明为static。

  声明为static的变量实质上就是全局变量。当声明一个对象时,并不产生static变量的拷贝,而是该类所有的实例变量共用同一个static变量。声明为static的方法有以下几条限制:

它们仅能调用其他的static 方法。

它们只能访问static数据。

它们不能以任何方式引用this 或super(关键字super 与继承有关,在下一章中描述)。

  如果你需要通过计算来初始化你的static变量,你可以声明一个static块,Static 块仅在该类被加载时执行一次。下面的例子显示的类有一个static方法,一些static变量,以及一个static 初始化块:

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

一旦UseStatic 类被装载,所有的static语句被运行。首先,a被设置为3,接着static 块执行(打印一条消息),最后,b被初始化为a*4 或12。然后调用main(),main() 调用meth() ,把值42传递给x。3个println ( ) 语句引用两个static变量a和b,以及局部变量x 。

  注意:在一个static 方法中引用任何实例变量都是非法的。

  下面是该程序的输出:

Static block initialized.
x = 42
a = 3
b = 12

在定义它们的类的外面,static 方法和变量能独立于任何对象而被使用。这样,你只要在类的名字后面加点号运算符即可。例如,如果你希望从类外面调用一个static方法,你可以使用下面通用的格式:

classname.method( )

这里,classname 是类的名字,在该类中定义static方法。可以看到,这种格式与通过对象引用变量调用非static方法的格式类似。一个static变量可以以同样的格式来访问——类名加点号运算符。这就是Java 如何实现全局功能和全局变量的一个控制版本。

  下面是一个例子。在main() 中,static方法callme() 和static 变量b在它们的类之外被访问。

class StaticDemo {   
static int a = 42;   
static int b = 99;   
static void callme() {   
 
System.out.println("a = " + a);   
}   
}   
 
class StaticByName {   
 
public static void main(String args[]) {   
StaticDemo.callme();   
System.out.println("b = " + StaticDemo.b);   
}   
}

下面是该程序的输出:

a = 42
b = 99

static成员是不能被其所在class创建的实例访问的。

如果不加static修饰的成员是对象成员,也就是归每个对象所有的。

加static修饰的成员是类成员,就是可以由一个类直接调用,为所有对象共有的。


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