Friday, June 24, 2011

What is use of parameterized constructor in abstract class? As Abstract classes cannot be instantiated



public abstract class ABC
{

int _a;

  public ABC(int a)
  {
    _a = a;

   }

public abstract void computeA();

};
The above question is little bit tricky, it wants to make you confuse by emphasizing on keyword “Abstract”, where as it has got nothing to do with abstract class.
First of all its essential to understand the constructor call chain. Whenever an object of a class created, its constructor gets called and that constructor calls its parent class’s constructor then this calling chain continuous till super most class’s constructor get called, then first the super most class’s constructor gets executed first then its child class’s constructor (of same chain) and at last the constructor of class whose object has been created will execute.
In the above example scenario where we have only parameterized constructor and no default “Non Parameterized” constructor, the child/inherited class will have to call constructor of its parent abstract class and will have to pass parameters in it.
Like:
public class Foo : ABC
{
    // Always pass 123 to the base class constructor
    public Foo() : base(123)
    {
    }
}
So you don't necessarily need to pass any information to the derived class constructor, but the derived class constructor must pass information to the base class constructor, if that only exposes a parameterized constructor. Also the child class have to override all abstract functions of its parent class.

Compiled By: Rajesh Rolen

Share This!


Powered By Blogger · Designed By Seo Blogger Templates