Hi,
I am trying to demonstrate Polymorphism using below code.
When I run the code I want to get below.
"Hello from ClassA"
"Hello from Classb"
What am I doing wrong?
Thanks,
using System;
namespace Polymorphism
{
public class Program
{
public static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
Object[] classes = new Object[] {a, b};
foreach (Object obj in classes)
{
Console.WriteLine(obj.Hello());
}
}
}
public class ClassA
{
public string Hello()
{
return "Hello from ClassA";
}
}
public class ClassB
{
public string Hello()
{
return "Hello from ClassB";
}
}
}
pvdg42 - 28 Nov 2006 16:23 GMT
> Hi,
>
[quoted text clipped - 45 lines]
> }
> }
Polymorphic behavior only occurs when classes are related through
inheritance. Your two classes are independent.
pvdg42 - 28 Nov 2006 16:36 GMT
> Hi,
>
[quoted text clipped - 8 lines]
>
> Thanks,
Here's the code you need:
namespace Polymorphism
{
public class Program
{
public static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
//Object[] classes = new Object[] {a, b};
// Instead, try
ClassA[] classes = new ClassA[] { a, b };
foreach (ClassA obj in classes)
{
Console.WriteLine(obj.Hello());
}
}
}
public class ClassA
{
public virtual string Hello() // note virtual
{
return "Hello from ClassA";
}
}
public class ClassB : ClassA // note the inheritance specification
{
public override string Hello() // note override
{
return "Hello from ClassB";
}
}
}
tantan - 08 Dec 2006 09:31 GMT
maybe you do not understand what the Polymorphism really is :) you can not
invoke the method that the baseclass does not have.
> Hi,
>
[quoted text clipped - 45 lines]
> }
> }
keyoke - 04 Mar 2007 16:40 GMT
Hi,
Here is an example of poly you are assigning your class to a type of object
which does not contain a "Hello" method if you were to cast it back to your
ClassA or ClassB it would then know that this method exists hop my code below
will shed some light.
cheers
keyoke.
using System;
namespace Polymorphism
{
public class Program
{
public static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
baseClass[] classes = new baseClass[] { a, b };
foreach (baseClass obj in classes)
{
Console.WriteLine(obj.Hello());
}
}
}
public class ClassA:baseClass
{
public ClassA()
{
base._message = "Hello from ClassA";
}
}
public class ClassB:baseClass
{
public ClassB()
{
base._message = "Hello from ClassA";
}
}
public class baseClass
{
public string _message;
public string Hello()
{
return _message;
}
}
}
>Hi,
>
[quoted text clipped - 45 lines]
> }
>}