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

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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值