Problem in interfaces (polymorphism) C #
I have two classes that have some common methods like funcA (), funcB ()
and some methods are only related to its class ...
what i did was testInterface was created
public interface TestInterface
{
void funcA()
void funcB()
}
public class ClassA : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassA FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassA FuncB()");
}
public void myFuncA()
{
Console.WriteLine("This is My Own Function A");
}
}
public class ClassB : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassB FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassB FuncB()");
}
public void myFuncB()
{
Console.WriteLine("This is My Own Function B");
}
}
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
}
as you can see above two classes. I have two functions, myFuncA () and myFuncB (), are not part of the interface. they belong only to their class.
how can i call them from the main method. where i create a TestInterface object and initialize it with some child class.
I actually have separate classes in the DAL.
they have some common methods. and some methods associated with their own class.
I want to implement a Factory pattern on this.
What should I do now?
source to share
is it good to add methods of ClassA and ClassB into interface and provide null implementation in other class?
like
public interface TestInterface
{
void funcA();
void funcB();
void myFuncA();
void myFuncB();
}
public class ClassA:TestInterface
{
public void funcA()
{
// some code here
}
public void funcB()
{
// some code here
}
public void myFuncA()
{
// my own code here
}
public void funcB()
{
// null implementation
}
}
and vice versa, in ClassB
source to share
If you are asking if you can do something like:
public static void Main(string[] a)
{
TestInterface test = new ClassA();
test.myFuncA();
}
the answer is no. You will need to migrate it to ClassA first. The fact that you think you need to do this indicates that there might be something wrong with your design.
source to share
Create a new interface for ClassA and ClassB and you just need to pass the class to the correct interface to see the new features.
public class ClassA : TestInterface, TestInterfaceA {
}
So when you get a specific instance, just move it to TestInterfaceA to see the functions specific to that class.
source to share
Mohsen. I am really confused by your question.
if you just want to call MyFuncA () or MyFuncB () you have to instantiate your own coupons like
ClassA a = new ClassA();
a.FuncA(); //interface member
a.FuncB(); // interface member
a.MyFuncA(); //class A Member
I can't undrestand why are you trying to instantiate your interface and then calling the subclass methods !!!! I'm right? or Imisunderstood your problem?
source to share