详细讲解方法重写的注意事项,子类与父类代码的执行顺序

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
{
	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);

	}
}
打印1、0

这是因为静态变量的初始化顺序是按照代码顺序来进行的。一开始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

说明先初始化父类的静态属性在执行自己的静态属性,再是父类的构造方法再是自己的构造方法。



发布了33 篇原创文章 · 获赞 6 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章