1.下面的程序输出是什么?为什么?
public class Parent {
public void test(ArrayList list) {
System.out.println("invoke parent's test method");
} public static void main(String[] args) {
Child a = new Child();
ArrayList list = new ArrayList();
a.test(list);
}
}class Child extends Parent {
public void test(List list) {
System.out.println("invoke child's test method");
}
}2.下面的程序输出是什么?为什么?
public class Parent {
public void test(List list) {
System.out.println("invoke parent's test method");
} public static void main(String[] args) {
Child a = new Child();
ArrayList list = new ArrayList();
a.test(list);
}
}class Child extends Parent {
public void test(List list) {
System.out.println("invoke child's test method");
}
}

解决方案 »

  1.   

    第一个的输出:invoke parent's test method
    第二个的输出:invoke child's test method
    其原因:第一个程序的子类方法被隐藏
            第二个程序的父类方法被覆盖
      

  2.   

    第一个程序:
        尽管子类有一个和父类同名的方法但是其参数类型不同,这样就没有能把父类的同名方法覆盖掉,在主方法中为子类的实例传进去的是一个ArrayList类型的参数,那么理所当然地会调用父类中的方法。你可以试把程序中的ArrayList test=new ArrayList()改成List test=new ArrayList(),结果还是一样,因为虽然声明为List,但test仍然是ArrayList的一个实例所以同样会调用父类的方法(这一点在JAVA编程思想中有较详细的说明)。
    第二个程序:
        因为子类中有一个完全与父类相同的方法,所以父类中的方法被覆盖,会调用子类中的方法。
      

  3.   

    第一个编译不能通过:Reference to test is ambiguous
    To Student02370236:
    如果将ArrayList test=new ArrayList()改成List test=new ArrayList()则可编译通过,并且调用的是子类的方法:)
      

  4.   

    1,invoke parent's test method
     
    由于引数不同,子类重载了父类的test(),传入ArrayList对象,于是调用父类的test(ArrayList list)2,invoke child's test method引数相同,子类覆写了父类的test(),要想调用父类的test方法,只能用super.test(List list)别无他法
      

  5.   

    TO cleansunshing(中文):
    第一个我是编译通过了的,不知你是用的什么工具,我是用EDITPLUS+JDK1.5...
      

  6.   

    第一个编译通过,第二个不行。
    public void test(List list) 改成public void test(ArrayList list) 通过。