जगदीश खोलिया: Abstract class

Wednesday, July 20, 2011

Abstract class

Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case i which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classes must define the missing pieces.

Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.

In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has tow derived abstract classe Shape2D & Shape3D inherites the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherites from Shape2D, and another group of classes Sphere, Cylinder & Cube inherites from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw().

A class is made abstract by declaring it with Keyword abstract.


public abstract class Shape
    //...Class implementation

    public abstract void Draw(int x, int y)
        //this method mustn't be implemented here.
        //If we do implement it, the result is a Syntax Error.

public abstract class Shape2D : Shape
    //...Class implementation
    //...you do not have to implement the the method Draw(int x, int y)

public class Cricle : Shape2D
    //here we should provide an implemetation for Draw(int x, int y)
    public override void Draw(int x, int y)
        //must do some work here

Difference between an abstract method & virtual method:

Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

important Notes:

(a)Any Class with abstract method or property in it must be declared abstract

(b)Attempting to instantiate an object of an abstract class retults in a compilation error


Shape m_MyShape = new Shape(); //it is Wrong to that.
But we can do that.
Shape m_MyShape = new Circle(); // True
Shape m_MyShape; 

declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class

Circle m_MyCircle = new Circle();
m_MyShape  = m_MyCircle; // Also True
(d)An abstract class can have instance data and non-abstract methods -including constructors-.
Post a Comment