<an*******@discussions.microsoft.com> wrote in news:1d96c01c423cd$59470170
$a*******@phx.gbl:
Hi all
I have a class Parent, and two child classes class Child1
and class Child2 derived from Parent class.
In Parent class there is a method that will instantiate
child classes based on the input parameters it received.
I am able to instantiate my child class from the Parent
class, but not able to call the child class methods from
the Parent class by doing this.
Child1 ch1 = new Child1();
ch1.SomeMethod();
I think by changing the access level of SomeMethod() to
something like internal, I will be able to call the child
method from the parent class. But, I need to know if this
is the right way to do? Does it violate any OOP
recommendations? or can you recommend some other best
pratice? Thanks a lot for your help.
Your idea of having the parent creating childs (Despite the
similarities in nature ;)) is not that great. Parent-child relations have
to be seen as: child is-a parent, and thus adds specialization to parent.
It's also not appropriate to call methods of a child class in a
parent. If you want to do that, you should do it like this:
public class Parent
{
//...
public void Foo()
{
object var = Bar();
// other code
}
public abstract object Bar();
}
now, in child1 and child2, you 'plug in' the code for Bar:
public class Child1:Parent
{
//...
public override object Bar()
{
object var=null;
// do some stuff
return var;
}
}
This way you can call code in parent which is implemented in a
child class. This is called the 'strategy pattern'.
If you want to produce various classes, you should use a factory
class. A factory simply creates objects based on input and doesn't have
any relation to the objects created.
Frans.
--
Get LLBLGen Pro, the new O/R mapper for .NET:
http://www.llblgen.com
My .NET Blog:
http://weblogs.asp.net/fbouma
Microsoft C# MVP