Reputation: 21855
I have the following inheritance:
class A
{
void Configure(object param1) {...};
}
class B : A
{
void Configure(object param1) {...}; // The method is not defined in B, it is available from the base class. This is just the desired interface of class B
}
class C : A
{
void Configure(object param1, object param2) {...};
}
I don't want class C to have a Configure with param1 visible as in this case it will leave the object incomplete.
I tried overriding but override cannot change the visibility.
The only approach I found is calling the class A method protected void ConfigureBase(object param1) {...};
and making method Configure of class B call ConfigureBase.
As I'm not completely happy with this design as it makes me redefine on each class the Configure is there a standard way of handling this?
Upvotes: 1
Views: 130
Reputation: 203812
This is not possible. You could possibly have the method just throw an exception so it couldn't be used, but one of the fundamental principles of inheritance in programming is that a child can always be treated as if it were of it's parent's type. What should the following do:
A obj = new C();
obj.Configure(new object());//should this work, or not?
By design, there is no way to restrict a child to not be able to do something it's parent could do. You would need to more fundamentally re-design your program if C
really shouldn't have access to a Configure(object obj)
method. This could possibly mean that C
really shouldn't extend A
(It might make sense for both A
and C
to implement a common interface.), or just that Configure
really shouldn't be a public method of that type. Without knowing more, it's hard to suggest alternatives.
Upvotes: 5
Reputation: 726489
is there a standard way of handling this?
Yes: make configuration process part of the initialization.
Instead of exposing Configure
, perform all initialization in the constructor. This will let your classes expose only the alternatives that make sense:
class A {
public A(object param1) {...};
}
class B : A {
public B(object param1) : base(param1) {...}; // This re-exposes A's constructor
}
class C : A {
// Note that A(param1) constructor is not available, even though C inherits A
public C(object param1, object param2) : base(param1) {...};
}
Upvotes: 2