java多态练习题
一、选择
- 下列代码的运行结果为: (C)
public class Animal {
public void show() {
System.out.println(“我是动物”);
}
}
public class Tiger extends Animal{
public void show() {
System.out.println(“我是老虎”);
}
}
public class Dog extends Animal{
public void show() {
System.out.println(“我是哈士奇”);
}
}
public class Test {
public static void main(String[] args) {
Animal one = new Animal();
one.show();
Animal two = new Tiger();
two.show();
Animal three = new Dog();
three.show();
}
}
A. 我是动物
B. 编译错误
C. 我是动物
我是老虎
我是哈士奇
D. 我是动物 我是老虎 我是哈士奇
-
创建一个父类Animal,一个子类Cat,Animal three = new Cat();不是 (C)
A. 向上转型
B. 自动转型
C. 向下转型
D. 隐式转型 -
下列代码怎么修改可以使其成功运行:(A)
public class Animal {
public void eat() {
System.out.println(“动物吃~~”);
}
}
public class bird extends Animal{
public void eat() {
System.out.println(“鸟吃虫子”);
}
public void fly() {
System.out.println(“鸟儿正在飞”);
}
}
public class Test {
public static void main(String[] args) {
Animal one = new bird(); //1
one.eat(); //2
one.fly(); //3
}
}
A. 删除掉标注3位置的one.fly( )
B. 标注1的Animal one=new Bird()修改为Animal one=new Animal()
C. 删除掉标注2位置的one.eat( )
D. 标注1的Animal one=new Bird()修改为Bird one=new Animal()
-
下列关于instanceof说法不正确的是 (C)
A. instanceof 的返回值为true和false
B. instanceof可以用来判断对象是否可满足某个特定类型
C. 可以通过“A instanceof B"表示 A 类可以转型为B类
D. instanceof可放在if语句的条件表达式中 -
已知父类Person,子类Man。判断类Person的对象person1是否满足类Man的实例特征,正确的语 (B)
句为
Animal an = new Animal();
bird bi = new bird();
if (bi instanceof Animal){
System.out.println(“可以转换”);
}
A. if (person1 instanceof Man)
B. if (man1 instanceof Person)
C. if (Person instanceof man1)
D. if (Man instanceof person1)
-
在Java中,多态的实现不仅能减少编码的工作量,还能大大提高程序的可维护性及可扩展性,那 (B)
么实现多态的步骤包括以下几个方面除了
A. 子类重写父类的方法
B. 子类方法设置为final类型
C. 定义方法时,把父类类型作为参数类型;调用方法时,把父类或子类的对象作为参数传
D. 运行时,根据实际创建的对象类型动态决定使用哪个方法 -
下面代码运行测试后,出现的结果是 (D)
public class Father {
public void show() {
System.out.println(“父亲”);
}
}
public class Son extends Father{
public void show() {
System.out.println(“儿子”);
}
}
public class Daughter extends Father{
public void show() {
System.out.println(“女儿”);
}
}
public class Test {
public static void main(String[] args) {
Father s = new Son();
Father d = new Daughter();
Son s1 = (Son)s;
s1.show();
Daughter d1 = (Daughter)s;
d1.show();
}
}
A. 编译错误,错误位置在第一行
B. 编译错误,错误位置在第二行
C. 第一行和第二行都运行成功,输出结果为
儿子
女儿
D. 编译成功,但运行报错,错误位置在第二行
二、编程
- 应用继承和多态的思想,编写动物类,成员方法是动物叫声。写三个具体的类(猫、狗、羊),
它们都是动物类的子类,并重写父类的成员方法。编写测试类,随机产生三种具体动物,调用叫
声这个方法