gpt4 book ai didi

java - 创建子类(特定)或父类(super class)(通用)类型的对象?

转载 作者:行者123 更新时间:2023-12-01 17:29:02 25 4
gpt4 key购买 nike

使用下面的代码:

public class Animal {
....// class stuff here
}

public class Cat extends Animal {
....// class stuff here
}

当尝试创建一个新的 Cat 对象时,有什么区别?:

    Cat myCat = new Cat(); //and
Animal myCat = new Cat();

我之前读过一些列表,您应该在左侧声明最通用的列表(即

List<String> = new LinkedList<String>(); )这样,如果您想更改实现以使用 ArrayList 来代替,则需要更改的代码就会更少。

在所有情况下,您是否都应该始终在左侧声明最通用(最不具体)的内容(在本例中为 Animal myCat = new Cat(); )?

最佳答案

创建的内容没有区别。唯一的区别在于引用的类型。如果你引用了 Animal,并尝试使用 Animal 中没有的 Cat 方法,编译器将给出错误。如果您调用 Cat 中被重写(注意:与重载不同)的方法,它将正确调用 Cat 的方法,即使引用的是 Animal。

关于java - 创建子类(特定)或父类(super class)(通用)类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12818475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com