抽象类如何有引用但没有对象? [英] How can abstract classes have references but not objects?

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

问题描述

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

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,这是一个从 Account 继承的非抽象类,但您不能让它指向 SavingsAccountcode>new Account(),因为您实际上无法实例化 Account.

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天全站免登陆