繁体   English   中英

调用子类构造函数时来自子类或超类的数据类型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM