我的漫漫程序之旅

专注于JavaWeb开发
随笔 - 39, 文章 - 310, 评论 - 411, 引用 - 0
数据加载中……

2007最后一套JAVA面试题(继承)

继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
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);
    }

    
}


输出结果:
parent static code
child 
static
 code
***************

Parent constructor
Parent a
=10
Child constructor
Child var a
=20

由此可看出在还没有实例化类的时候(注意*号)已经执行了static代码块。
顺序是先父类后子类.
然后才调用父类的构造方法,再调用子类的构造方法.就是这个顺序了.
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);
    }

    
}



posted on 2007-12-28 10:36 々上善若水々 阅读(2707) 评论(7)  编辑  收藏 所属分类: Java笔试与面试

评论

# re: 2007最后一套JAVA面试题(继承)[未登录]  回复  更多评论   

顺序好像是这个样子的啊
parent static code
***************
child static code
Parent constructor
Parent a=10
Child constructor
Child var a=20
2008-02-15 14:09 | 1

# re: 2007最后一套JAVA面试题(继承)[未登录]  回复  更多评论   

child并不是内部类
2008-02-15 14:15 | 1

# re: 2007最后一套JAVA面试题(继承)  回复  更多评论   

@1
请动手后再回复.
2008-02-17 21:49 | 々上善若水々

# re: 2007最后一套JAVA面试题(继承)  回复  更多评论   

@1
论主的答案是正确的,要求把两个类放在一个java文件里才行
2008-03-12 20:54 | 天才

# re: 2007最后一套JAVA面试题(继承)  回复  更多评论   

parent static code
***************
child static code
Parent constructor
Parent a=10
Child constructor
Child var a=20
肯定是这样的,我运行过了。
2008-04-20 11:41 | nene

# re: 2007最后一套JAVA面试题(继承)  回复  更多评论   

我也动手试过了

无论把Parent、Child分开放在两个java文件中,还是放在一个java文件中,执行后的结果都和楼上的一样。

ps: 我的 java 版本是1.6
2008-05-15 22:50 | gvn

# re: 2007最后一套JAVA面试题(继承)  回复  更多评论   

对。。程序从main90方法入口。后面的子类都没有实例化调用。。
2008-08-16 21:20 | shady

只有注册用户登录后才能发表评论。


网站导航: