简体   繁体   English

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

[英]Datatype from subclass or superclass while calling the subclass constructor?

I'm a novice with java and I tried to make a simple polymorphism program.我是 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 }

I was wondering if there is a difference between this and changing the datatype from line 7 to Cow -> Cow cow = new Cow();我想知道这与将数据类型从第 7 行更改为 Cow -> Cow cow = new Cow();之间是否有区别and the datatype from line 8 to Sheep -> Sheep sheep = new Sheep();以及从第 8 行到 Sheep -> Sheep sheep = new Sheep(); I'm very curious because the output is exactly the same.我很好奇,因为 output 完全一样。

There is no difference, cow variable is used just to add it to a ArrayList<Animal> .没有区别, cow变量仅用于将其添加到ArrayList<Animal>

There could be a difference according to a specific usage case since a Cow variable could have additional methods which are not present in Animal but semantically they'll be behave equivalently.根据特定的用例可能会有所不同,因为Cow变量可能具有其他方法,这些方法在Animal中不存在,但在语义上它们的行为相同。

The only difference is what you are allowed to invoke on the cow variable.唯一的区别是你可以在cow变量上调用什么。

In general it's always better to use the least specific type you can so that you are sure you are not using any specific feature that you wouldn't want to use.一般来说,最好使用最不具体的类型,这样您就可以确定您没有使用任何您不想使用的特定功能。 This same principle applies to animals variables, a better declaration would be:同样的原则也适用于animals变量,更好的声明是:

List<Animal> animals = new ArrayList<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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