简体   繁体   中英

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 .

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.
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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