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.....
}
}
If I can't inherit constructors. How can I prevent that someone will NOT FORGET to implement that specific child class constructor ????
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With