代码演示:
public class usingAttribute
{
static String str1=“string1”;
static String str2;
String str3=“string3”;
String str4;
static{//static语句用于初始化static成员变量,是最先运行的语句块
printStatic(“before static”);
str2=“string2”;
printStatic(“after static”);
}
public static void printStatic(String title)
{
System.out.println("------"+title+"-----");
System.out.println(“str1=”"+str1+""");
System.out.println(“str2=”"+str2+""");
}
public usingAttribute()
{
print("before constructor");
str4="string4";
print("after constructor");
}//定义了一个构造方法usingAttribute(),在这个方法中,使用了类中的各个属性。构造方法与类同名,且无返回值(包括void),它的主要目的是创建对象。
public void print(String title)
{
System.out.println("-----"+title+"-----");
System.out.println("str1=\""+str1+"\"");
System.out.println("str2=\""+str2+"\"");
System.out.println("str3=\""+str3+"\"");
System.out.println("str4=\""+str4+"\"");
}
public static void main(String[] args){
System.out.println();
System.out.println("-----创建usingAttribute对象-----");
System.out.println();
new usingAttribute();//使用关键字new和构造方法usingAttribute()来创建一个匿名对象;
}
}
由输出结果可以看出,Java类属性和对象属性的初始化顺序如下:
(1)类属性(静态变量)定义时的初始化,如范例中的static String str1=“string1”;
(2)static块中的初始化代码,如范例中的static{}中的str2=“string-2”;
(3)对象属性(非静态变量)定义时的初始化,如范例中的String str3=“string3”;
(4)构造方法(函数)中的初始化代码,如范例构造方法中的str4=“string4”.
当然这里只是为了演示java类中的属性和对象属性的初始化顺序。在实际的应用中并不建议在类中定义属性时实施初始化,如例子中的字符串变量:“str1”,“str3”.
请注意,被static修饰的变量称为类变量(class variables),它们被类的实例所共享。也就是说,某一个类的实例化改变了这个静态值,其他这个类的实例也会受到影响。而成员变量(member variable)则是没有被static修饰的变量,为实例所私有,也就是说,每个类的实例都有一份自己专属的成员变量,只有当前实例才可更改它们的值。
static是一个特殊的关键字,其在英文中直译就是“静态”的意思。它不仅用于修饰属性(变量)、成员,还可以用来修饰类中的方法。被static修饰的方法,同样表明它是属于这个类共有的,而不是属于该类的单个实例,通常把static修饰的方法也称为类方法。