Java代码执行顺序

我们先看下面两个类

 

public class Parent {

	// 08
	public String tag = "parent";
	// 01
	public static String staticTag = "staticParent";

	// 07
	public Parent() {
		// 09
		Test();
	}

	// 02
	static {
		System.out.println("static_parent:" + staticTag);
	}

	// 被子类复写,没有调用
	public void Test() {
		System.out.println("Parent_test1:" + tag);
	}
}

 

 

 

子类

 

 

 

 

public class Child extends Parent {

	// 06
	public Child() {
		// 12
		Test();
	}

	// 11
	public String tag = "child";
	// 03
	public static String staticTag = "staticChild";
	// 04
	static {
		System.out.println("static_child:" + staticTag);
	}

	public void Test() {
		// 10(父)
		// 13(子)
		System.out.println("Child_test1:" + tag);
	}

	public static void main(String[] args) {
		// 05
		new Child();
	}

}

看一下执行的结果

 

static_parent:staticParent
static_child:staticChild
Child_test1:null
Child_test1:child

总结:1,先执行父类的静态变量和代码块,在执行子类的静态变量和代码块

 

    2,接着执行父类的变量和构造方法里面的方法

    3,接着执行子类的变量和构造方法里面的方法
我们在修改一下main方法

 

	public static void main(String[] args) {
		Parent mParent = new Child();
		mParent.Test();
		System.out.println(mParent.tag);
	}

执行一下

 

 

static_parent:staticParent
static_child:staticChild
Child_test1:null
Child_test1:child
Child_test1:child
parent

我们可以看到,子类可以覆盖父类的方法,但不能覆盖父类的变量。

静态变量和静态初始化块是依照他们在类中的定义顺序进行初始化的。同样,变量和初始化块也一样。

下面再来看几个特殊的,

    private int aaa() {
        try {
//           int w= 1/0;
            return 1;
        } catch (Exception e) {

        } finally {
            return 2;
        }
//        return 3;
    }

如果finally中有return,那么函数的最后是不能有return的,否则要报错,上面这种情况返回的是2,

    private int aaa() {
        try {
//           int w= 1/0;
            return 1;
        } catch (Exception e) {

        } finally {
//            return 2;
        }
        return 3;
    }

上面这种情况返回的是1,

    private int aaa() {
        try {
           int w= 1/0;
            return 1;
        } catch (Exception e) {

        } finally {
//            return 2;
        }
        return 3;
    }

上面这种情况返回的是3,因为上面出现了异常。

    private int aaa() {
        try {
           int w= 1/0;
            return 1;
        } catch (Exception e) {

        } finally {
            return 2;
        }
//        return 3;
    }

上面这种情况返回的是2,所以会得出一个结论就是只要finally有return,就会返回finally中return的值。

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据结构和算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值