Groups | Blog | Home
all groups > dotnet academic > november 2006 >

dotnet academic : Polymorphism


C
11/28/2006 7:36:01 AM
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
11/28/2006 10:23:43 AM

[quoted text, click to view]

Polymorphic behavior only occurs when classes are related through
inheritance. Your two classes are independent.

pvdg42
11/28/2006 10:36:58 AM

[quoted text, click to view]
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
12/8/2006 12:00:00 AM
maybe you do not understand what the Polymorphism really is :) you can not
invoke the method that the baseclass does not have.

[quoted text, click to view]

keyoke
3/4/2007 4:40:31 PM
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;
}
}
}

[quoted text, click to view]
AddThis Social Bookmark Button