首页 > 试题广场 >

下列代码输出结果为( ) class Animal { pu

[单选题]
下列代码输出结果为(      )
class Animal {
    public void show(Dog dog){
        System.out.println("a");
    }

    public void show(){
        System.out.println("b");
    }
}

class Dog extends Animal {
    public void show(Dog dog){
        System.out.println("c");
    }
    public void show(){
        System.out.println("d");
    }
}


public class Base {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.show(new Dog());
        animal.show();
    }
}
  • a,b
  • a,d
  • c,b
  • c,d
1. 首先分析代码中的多态行为: - 当执行 Animal animal = new Dog(); 时, animal 是 Animal 类型,但实际指向的是 Dog 类的对象。 - 对于 animal.show(new Dog()); : - 因为在 Animal 类中有 show(Dog dog) 方法,在 Dog 类中重写了这个方法。根据多态性,会调用 Dog 类中重写后的 show(Dog dog) 方法,所以会输出 c 。 - 对于 animal.show(); : - 这里在 Animal 类中有 show() 方法,在 Dog 类中也重写了 show() 方法。同样根据多态性,会调用 Dog 类中重写后的 show() 方法,所以会输出 d 。 2. 然后得出输出结果: - 输出结果为 c,d 。 所以答案是D。
发表于 2024-11-12 10:36:42 回复(0)
考察多态父类中不存在的方法,向上转型后,不能丢失该方法父类中存在的方法,子类进行了重写,在调用时,使用子类的方法
发表于 2021-09-16 16:40:05 回复(0)