实现多态参数传递采用什么方式,如果没有使用某种方式原因是什么;

如题所述

第1个回答  推荐于2016-12-01
你问的问题不是很明显:
多态作为参数传递不是说采用什么方式。多态作为参数时,在函数中是以父类类型作为形参。当实际上调用此函数的时候,就可以传递继承该父类的子类,这样就产生了多态的效果。简单的例子如下:

public class Factorial {

//在此方法中,将Vehicles作为一个参数,
//此处如果用Bus作为参数就根本没有意义了,因为不能实现多态
public void goMethod(Vehicles v) {
v.run() ;
}

public static void main(String[] args) {
Factorial f = new Factorial() ;
//分别定义父类和子类
Vehicles v = new Vehicles() ;
Bus b = new Bus() ;
//定义了一个向上(父类)转型 保留父类的特性
Vehicles vb = new Bus() ;

f.goMethod(v) ;
f.goMethod(b) ;

f.goMethod(vb) ;
}
}

//父类定义一个方法run()
class Vehicles {
public void run() {
System.out.println("-----run-------") ;
}
}
//子类继承父类并且重写一个方法run()
class Bus extends Vehicles {
public void run() {
System.out.println("-----run with bus-----") ;
}
}

输出结果:
-----run-------
-----run with bus-----
-----run with bus-----本回答被提问者采纳
相似回答