多态(Java和Rust)
一、Java的多态
父类引用指向子类对象;
List list = new ArrayList();
父类的接口方法,取决于实现子类;
二、Rust的多态(dyn)
struct Sheep{}
struct Cow{}
pub trait Noise{
fn noise(&self);
}
impl Noise for Sheep {
fn noise(&self) {
println!("baaaaah!")
}
}
impl Noise for Cow {
fn noise(&self) {
println!("moooooo!!")
}
}
fn main(){
let mut noise : Box<dyn Noise> =Box::new(Sheep{});
noise.noise();
noise = Box::new(Cow{});
noise.noise();
}