Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a constructor only accessible by base class?

If I want a constructor that is only accessible from child classes I can use the protected key word in the constructor.

Now I want the opposite.

My child class should have an constructor that can be accessed by its base class but not from any other class.

Is this even possible?

This is my current code. the problem is that the child classes have a public constructor.

public abstract class BaseClass
{
    public static BaseClass CreateInstance(DataTable dataTable)
    {
        return new Child1(dataTable);
    }
    public static BaseClass CreateInstance(DataSet dataSet)
    {
        return new Child2(dataSet);
    }
}

public class Child1 : BaseClass
{
    public Child1(DataTable dataTable)
    {
    }
}

public class Child2 : BaseClass
{
    public Child2(DataSet dataSet)
    {
    }
}
like image 942
Jürgen Steinblock Avatar asked May 24 '12 13:05

Jürgen Steinblock


1 Answers

I think you have two options:

  1. Make the child constructor internal. This means it will be accessible from all types in the same assembly, but that should be enough in most cases.
  2. Make the child classes nested in the base class:

    public abstract class BaseClass
    {
        public static BaseClass CreateInstance(DataTable dataTable)
        {
            return new Child1(dataTable);
        }
    
        private class Child1 : BaseClass
        {
            public Child1(DataTable dataTable)
            {
            }
        }
    }
    

    This way, BaseClass can use the constructor, but no other outside type can do that (or even see the child class).

like image 93
svick Avatar answered Sep 24 '22 05:09

svick