1.父类与子类构造顺序问题
代码如下:
public class Main {
public static void main(String[] args) {
Father father = new Child();
}
}
class Father {
static {
System.out.println("Father static area");
}
{
System.out.println("Father dynamic area");
}
Father() {
System.out.println("Father Constructor");
}
}
class Child extends Father{
static {
System.out.println("Child static area");
}
{
System.out.println("Child dynamic area");
}
Child() {
System.out.println("Child Constructor");
}
}
输出结果为:
Father static area
Child static area
Father dynamic area
Father Constructor
Child dynamic area
Child Constructor
从输出结果可以看出执行顺序为:
- 父类静态代码块
- 子类静态代码块
- 父类动态代码块
- 父类构造函数
- 子类动态代码块
- 子类构造函数
2.函数参数重载
public class Help {
public static void main(String[] args) {
Father father = new Child();
Help help = new Help();
help.method(father);
}
public void method(Father father) {
System.out.println("This is father");
}
public void method(Child child) {
System.out.println("This is child");
}
public void method(InterFace interFace) {
System.out.println("This is InterFace");
}
}
class Father {
}
interface InterFace {
}
class Child extends Father implements InterFace {
}
根据引用类型进入相应的方法
This is father
3.子类成员变量是否可以覆盖父类成员变量
public class Help {
protected int a = 0;
public static void main(String[] args) {
Help help = new Help();
InnerClass innerClass = help.new InnerClass();
System.out.println(innerClass.a);
}
public class InnerClass extends Help {
protected int a = 1;
}
}
1
结果是可以覆盖的
4.try -> catch -> finally的执行顺序问题
/**
* Created by dly on 2018/9/5
*/
public class TestException {
public TestException() {
}
boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}
boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret; //try遇到return会跳转到finally
} catch (Exception e) {
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}
boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2, catch exception");
ret = false;
throw e; //往finally跳转, throw未执行,异常会被直接屏蔽
} finally {
System.out.println("testEx2, finally; return value=" + ret);
return ret;
}
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行结果
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false