2007最后一套JAVA面試題(繼承)
繼承時(shí)候類的執(zhí)行順序問(wèn)題,一般都是選擇題,問(wèn)你將會(huì)打印出什么?
package com.test;

public class Parent
{
//1
static int a = 1;
//2
static
{
a = 10;
System.out.println("parent static code");
}
//4
public Parent()
{
System.out.println("Parent constructor");
System.out.println("Parent a=" + a);
}
public static void main(String[] args)
{
System.out.println("***************");
Parent c = new Child();
}
}

class Child extends Parent
{
static int a = 2;
//3
static
{
a = 20;
System.out.println("child static code");
}
//5
public Child()
{
System.out.println("Child constructor");
System.out.println("Child var a=" + a);
}
}
輸出結(jié)果:
parent static code
child static code
***************
Parent constructor
Parent a=10
Child constructor
Child var a=20
由此可看出在還沒(méi)有實(shí)例化類的時(shí)候(注意*號(hào))已經(jīng)執(zhí)行了static代碼塊。
順序是先父類后子類.
然后才調(diào)用父類的構(gòu)造方法,再調(diào)用子類的構(gòu)造方法.就是這個(gè)順序了.
package com.test;

public class Parent
{
//1
static int a = 1;
//2
static
{
a = 10;
System.out.println("parent static code");
}
//4
public Parent()
{
System.out.println("Parent constructor");
System.out.println("Parent a=" + a);
}
public static void main(String[] args)
{
System.out.println("***************");
Parent c = new Child();
}
}

class Child extends Parent
{
static int a = 2;
//3
static
{
a = 20;
System.out.println("child static code");
}
//5
public Child()
{
System.out.println("Child constructor");
System.out.println("Child var a=" + a);
}
}












































輸出結(jié)果:








由此可看出在還沒(méi)有實(shí)例化類的時(shí)候(注意*號(hào))已經(jīng)執(zhí)行了static代碼塊。
順序是先父類后子類.
然后才調(diào)用父類的構(gòu)造方法,再調(diào)用子類的構(gòu)造方法.就是這個(gè)順序了.












































posted on 2007-12-28 10:36 々上善若水々 閱讀(2748) 評(píng)論(7) 編輯 收藏 所屬分類: Java筆試與面試