public class Test
{
public void changValue(String str)
{
str="xyz";
}
public static void main(String[] args)
{
String str="abc";
Test test= new Test();
test.changValue(str);
System.out.println(str);
}
}
打印“abc”
public class Test打印1、0
{
private static Test test = new Test();
public static int count1;
public static int count2 = 0;
private Test()
{
count1++;
count2++;
}
public static Test getInstance()
{
return test;
}
public static void main(String[] args)
{
System.out.println(Test.count1);
System.out.println(Test.count2);
}
}
这是因为静态变量的初始化顺序是按照代码顺序来进行的。一开始count1、count2在经过构造方法处理后的值都是1,接着count1没有进行再次赋值,往下执行到count2再次赋值成0.
<span style="font-size:10px;">public class Test
{
public static void main(String[] args)
{
new Child();
}
}
class Parent
{
static String name1 = "hello";
static
{
System.out.println("Parent static block");
}
public Parent()
{
System.out.println("Parent construct block");
}
}
class Child extends Parent
{
static String name2 = "hello";
static
{
System.out.println("Child static block");
}
public Child()
{
System.out.println("Child construct block");
}
}</span>
打印:
Parent static block
Child static block
Parent construct block
Child construct block
说明先初始化父类的静态属性在执行自己的静态属性,再是父类的构造方法再是自己的构造方法。