分享

java 难题

 moonboat 2010-11-23
Given:

class Bird {
  { System.out.print("bl "); }
  public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
  static { System.out.print("r1 "); }
  public Raptor() { System.out.print("r2 "); }
  { System.out.print("r3 "); }
  static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
  public static void main(String[] args) {
    System.out.print("pre ");
    new Hawk();
    System.out.println("hawk ");
  }
}

What is the result?

pre b1 b2 r3 r2 hawk

pre b2 b1 r2 r3 hawk

pre b2 b1 r2 r3 hawk r1 r4

r1 r4 pre b1 b2 r3 r2 hawk

r1 r4 pre b2 b1 r2 r3 hawk

pre r1 r4 b1 b2 r3 r2 hawk

pre r1 r4 b2 b1 r2 r3 hawk

The order of output cannot be predicted.

Compilation fails.

answer is : r1 r4 pre bl b2 r3 r2 hawk


public class InheritTest {

    private InheritTest inherit;

    @Before
    public void init() {
        inherit = new InheritTest();
    }

    public void sayInherit(Raptor obj) {
        System.out.println("obj is raptor");
    }

    public void sayInherit(Bird obj) {
        System.out.println("obj is Bird");
    }
    @Test
    public void inherit() {
        Raptor raptor = new Raptor();
        Hawk hawk = new Hawk();
        inherit.sayInherit(raptor);
        inherit.sayInherit(hawk);

    }
}

what will print out?

answer is :
obj is raptor
obj is raptor



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多