抽象类如何具有引用而不是对象? [英] How can abstract classes have references but not objects?

查看:168
本文介绍了抽象类如何具有引用而不是对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,你不能构造一个抽象类的对象,但你仍然可以有一个对象
引用类型是一个抽象类。当然,它引用的实际对象必须是
一个具体子类的实例:

Note that you cannot construct an object of an abstract class, but you can still have an object reference whose type is an abstract class. Of course, the actual object to which it refers must be an instance of a concrete subclass:

Account anAccount; // OK
anAccount = new Account(); // Error—Account is abstract
anAccount = new SavingsAccount(); // OK
anAccount = null; // OK

不理解为什么可以有一个抽象类的对象引用...


Not understanding why you can have an object reference to an abstract class...

推荐答案

当你有一个类型是抽象类的对象引用时,该引用并不意味着我引用一个抽象类。相反,它意味着我引用一些实际的对象,它是该抽象类的子类。这是为什么你可以参考 SavingsAccount ,这是一个非抽象类,从帐户 ,但是你不能指向新的帐户(),因为你实际上不能实例化帐户

When you have an object reference whose type is an abstract class, that reference doesn't mean "I'm referencing an abstract class." Instead, it means "I'm referencing some actual object that's a subclass of that abstract class." This is why you can have the reference refer to a SavingsAccount, which is a non-abstract class that subclasses from Account, but you can't have it point to a new Account(), since you can't actually instantiate Account.

请注意,引用本身不是抽象类的实际实例。

Note that the reference itself isn't an actual instance of the abstract class.

希望这有助于!

这篇关于抽象类如何具有引用而不是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆