简体   繁体   English

抽象类如何引用但不引用对象?

[英]How can abstract classes have references but not objects?

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... 不明白为什么你可以有一个抽象类的对象引用...

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 . 这就是为什么你可以让引用引用一个SavingsAccount ,它是一个从Account SavingsAccount的非抽象类,但你不能让它指向一个new Account() ,因为你实际上无法实例化Account

Note that the reference itself isn't an actual instance of the abstract class. 请注意,引用本身不是抽象类的实际实例。

Hope this helps! 希望这可以帮助!

The problem is that you cannot call abstract member routines. 问题是你不能调用抽象成员例程。
When you call 'new' you're actually calling the class's constructor. 当你调用'new'时,你实际上正在调用类的构造函数。
Because you're trying to call an abstract member function you get an error. 因为您尝试调用抽象成员函数,所以会出错。

You can reference an abstract class, because it is just a blueprint for a real class that derives from it. 可以参考一个抽象类,因为它只是为提炼出来的真正的类的蓝图。 A bit like an interface but with inheritance. 有点像接口但有继承。
Just like you cannot instantiate an interface you cannot instantiate an abstract class. 就像您无法实例化接口一样,您无法实例化抽象类。

This of course is part of polymorphism . 这当然是多态性的一部分。
The differences between abstract classes and interfaces are remarkably small, see: Interface vs Abstract Class (general OO) 抽象类和接口之间的差异非常小,请参阅: 接口与抽象类(通用OO)

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

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