我有抽象类:
public abstract class Owoc {
public Owoc(){};
private String name;
private double weight;
public String getName(){
return name;
}
public void setName(String newName){
this.name = newName;
}
...
子类Truskawka:
public class Truskawka extends Owoc {
public Truskawka(){
setName("truskawka");
setWeight(1);
}
public void growTruskawka() {
System.out.println(getName() + " is growing");
}
}
当我在下面的情况下遍历所有的Owocs时,如何在主类中调用方法growTruskawka():
owoc = owocFactory.makeOwoc(typeOfOwoc);
owoc.growTruskawka();
我试图施放,但它不起作用:java告诉"必需truskawka,发现Owoc"
(Truskawka) owoc = owocFactory.makeOwoc(typeOfOwoc);
答案 0 :(得分:1)
如果要使用多态,请将方法grow
放在基类(Owoc
)中,并在子类中覆盖它(如Truskawka
)。
例如,在Owoc
:
public void grow() {
System.out.println("grow() from Owoc");
}
在Truskawka
:
@Override
public void grow() {
System.out.println(getName() + " is growing");
}
然后,如果您有Truskawka
的实例,则调用grow
将执行其特定方法:
Owoc owoc = new Truskawka();
owoc.grow(); // this will print "truskawka is growing"