0
点赞
收藏
分享

微信扫一扫

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 条评论