c# - why abstract class cannot be instantiated ,what is the use of a class which cannot be instantiated -


i know , read abstract class , interface 1 point never understood that, use of class cannot instantiated. can use normal class , virtual method instead of abstract class? happen when instantiate base class?

you typically use abstract class when have set of common functionality shared between derived classes. is, cannot use interface because want provide default functionality.

take @ system.io.stream class. class provides common base functionality, requires specific types of streams implement members in order function. these members tagged abstract, indicates compiler , runtime there no suitable base-class implementation. non-abstract class derives abstract class must override inherited abstract members, class implements interface must implement members defined on interface.

in stream example, read() method abstract, readbyte() method not -- because readbyte() can implemented in terms of call read(). (although not optimally, why readbyte() virtual, more efficient implementation can optionally provided.) virtual members different, because do have implementation, can optionally overridden. abstract members have no implementation default, , must overridden.

in other words, methods on abstract class can use other abstract members on class, though have no implementation! because derived non-abstract class required provide implementation -- implementation guaranteed exist @ point method invoked. analogous how can use members of interface though members have no implementation on interface, because it's guaranteed object implementing interface must implement of members.

subclasses memorystream , filestream override of abstract methods form concrete class, , can instantiated. however, able store them in stream reference variable , treat them generic "black box" stream. allows declare method accepts stream object, , don't have care kind of stream is.

stream foo = new stream();       // invalid, stream abstract. stream foo = new memorystream(); // valid. 

so, summarize answers questions posed in title. abstract class cannot instantiated because may contain members abstract , have no implementation. use of abstract class twofold: first, subclassed , allow subclasses share common implementation of members, , second, allow instances of objects of subclasses used through references abstract class.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -