gpt4 book ai didi

java - 继承和创建对象

转载 作者:行者123 更新时间:2023-11-30 08:09:17 25 4
gpt4 key购买 nike

假设 Java 中有以下类:

TeachingAssistant extends Graduate

我可以制作一个Graduateobject 并在TeachingAssistant 中使用吗?示例

TeachingAssistant TA1 = new TeachingAssistant();
Graduate grad1 = new Graduate();
grad1 = TA1; //can I do this?
TA1 = grad1;// can I do this as well?

还假设A 类扩展 B 并实现 C我可以在 A 中创建 B 和 C 的对象吗?

最佳答案

给定

class TeachingAssistant extends Graduate{}
class Graduate{}

这总结了你能做什么/不能做什么(以及为什么)

TeachingAssistant t = new TeachingAssistant(); //OK
Graduate g = new Graduate(); //OK
Graduate gt = new TeachingAssistant(); //OK
TeachingAssistant tg1= new Graduate(); //Compile error: a Graduate is NOT ALWAYS a TeachingAssistant
TeachingAssistant tg2= (TeachingAssistant) new Graduate(); //Runtime error: as previous example
TeachingAssistant tg3= (TeachingAssistant)gt; //OK: gt is an object of type TeachingAssistant
//referenced by reference of type Graduate

关于java - 继承和创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32555164/

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