[英]Datatype from subclass or superclass while calling the subclass constructor?
我是 java 的新手,我嘗試制作一個簡單的多態程序。
public abstract class Animal {
public abstract void action();
}
public class Cow extends Animal {
@Override
public void action() {
System.out.println("Im a cow.");
}
}
public class Sheep extends Animal {
@Override
public void action() {
System.out.println("Im a sheep.");
}
}
1 import java.util.ArrayList;
2
3 public class Main {
4
5 public static void main(String[] args) {
6 ArrayList<Animal> animals = new ArrayList<Animal>();
7 Animal cow = new Cow();
8 Animal sheep = new Sheep();
9 animals.add(cow);
10 animals.add(sheep);
11
12 for (Animal animal : animals) {
13 animal.action();
14 }
15 }
16 }
我想知道這與將數據類型從第 7 行更改為 Cow -> Cow cow = new Cow();
之間是否有區別以及從第 8 行到 Sheep -> Sheep sheep = new Sheep();
我很好奇,因為 output 完全一樣。
沒有區別, cow
變量僅用於將其添加到ArrayList<Animal>
。
根據特定的用例可能會有所不同,因為Cow
變量可能具有其他方法,這些方法在Animal
中不存在,但在語義上它們的行為相同。
唯一的區別是你可以在cow
變量上調用什么。
一般來說,最好使用最不具體的類型,這樣您就可以確定您沒有使用任何您不想使用的特定功能。 同樣的原則也適用於animals
變量,更好的聲明是:
List<Animal> animals = new ArrayList<>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.