一、Class variables are shared among all instances of a class and can be accessed even in the absence of any instance. These variables are associated with the class--not with instances of the class--so they are logically part of the class data in the method area. Before a Java VirtualMachine uses a class, it must allocate memory from the method area foreach non-final class variable declared in the class.
类变量 static:所有对象可以用,存贮在方法区,而且是第一类使用时,进行初始化。如果一个对象改变这个值,哪么所有对象都能用新改变的值。
类常量 static final:存在常量池中,每一类有一个常量池,如果谁想用别的类常量,只要复制到自己的常量池中。
二、例子 :
package jvm.ex1; public class Examplelc { //类变量初始化 static int width; static int heigh=(int)(Math.random()*2.0); // This is the static initializer静态初始化 static { width = 3 * (int) (Math.random() * 5.0); } static void main(String[] args) { Examplelc test=new Examplelc(); } } |
三、什么时候会执行初始化
1、new 一个类
2、子类继承父类,会对父类初始化
3、直接调用 Examplelc.width。即调用类静态类变量
直接调用 Examplelc.静态方法。即调用类静态类方法。
四、以建立对象为例子:
类变量默认方法<clinit
// The code for height's class variable initializer beginshere// Invoke Math.random(), which willpush
三、初始化默认<clinit 方法,JVM自己调用。
All the class variable initializers and static initializers of a classare collected by the Java compiler and placed into one special method,theclass initialization method. In the Java class file, the classinitialization method is named "<clinit".
1、Initialization of a class consists of two steps:
1》Initializing the class's direct superclass (if any), if the direct superclass hasn't already
been initialized:如果父类未初始化,则初始化父类
2》Executing the class's class initialization method, if it has one