Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class > mandatory constructor for child classes [duplicate]

Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?

How can I write one abstract class that tells that is mandatory for the child class to have one constructor?

Something like this:

public abstract class FatherClass
{

    public **<ChildConstructor>**(string val1, string val2)
    {

    }

   // Someother code....
}

public class ChildClass1: FatherClass
{
    public ChildClass1(string val1, string val2)
    {
       // DO Something.....
    }
}

UPDATE 1:

If I can't inherit constructors. How can I prevent that someone will NOT FORGET to implement that specific child class constructor ????

like image 661
SmartStart Avatar asked Sep 08 '09 11:09

SmartStart


People also ask

How do you call an abstract class constructor in child class?

Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.

Can a child class have a constructor?

A subclass needs a constructor if the superclass does not have a default constructor (or has one that is not accessible to the subclass). If the subclass has no constructor at all, the compiler will automatically create a public constructor that simply calls through to the default constructor of the superclass.

Should abstract classes have constructors?

Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class.

Can abstract class have child class?

How to create child classes from an abstract class? Since we cannot create objects from abstract classes, we need to create child classes that inherit the abstract class code. Child classes of abstract classes are formed with the help of the extends keyword, like any other child class.


1 Answers

You cannot.

However, you could set a single constructor on the FatherClass like so:

protected FatherClass(string val1, string val2) {}

Which forces subclasses to call this constructor - this would 'encourage' them to provide a string val1, string val2 constructor, but does not mandate it.

I think you should consider looking at the abstract factory pattern instead. This would look like this:

interface IFooFactory {
    FatherClass Create(string val1, string val2);
}

class ChildClassFactory : IFooFactory
{
    public FatherClass Create(string val1, string val2) {
        return new ChildClass(val1, val2);
    }
}

Wherever you need to create an instance of a subclass of FatherClass, you use an IFooFactory rather than constructing directly. This enables you to mandate that (string val1, string val2) signature for creating them.

like image 198
Matt Howells Avatar answered Nov 11 '22 17:11

Matt Howells