In the following example I am using C#.
I have created an abstract class Base_Collection, and then I derive other classes from it (Book, Movie, Game). However, I don’t know how to add new methods that can be used for those new children classes without getting a compiler error.
namespace polymorphism_test_01
{
abstract class Base_Collection
{
public int id = 0;
public string title = "";
public Base_Collection() { }
}
}
namespace polymorphism_test_01
{
class Book : Base_Collection
{
public Book() { }
public override void Read_Book() { }
}
}
namespace polymorphism_test_01
{
class Game : Base_Collection
{
public Game() { }
public void Play_Game() { }
}
}
namespace polymorphism_test_01
{
class Movie : Base_Collection
{
public Movie() { }
public void Watch_Movie() { }
}
}
Calling book.Read_Book() doesn’t work in the following snippet, the compiler will output an error:
namespace polymorphism_test_01
{
class Program
{
public static void Main(string[] args)
{
Base_Collection book = new Book();
book.title = "The Dark Tower";
book.Read_Book();
Console.WriteLine(book.title);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Further to the answer from @Will (which is correct), you could structure your heirarchy a little better. For example, you do something different with each of the media types, but each type still gets consumed.
So change your base class to have an abstract base method called
Consume(), which is then overridden and actually implemented in each derived class, this way you can pass around instances of your base class and there is no need for casting to invoke theConsume()method on each media type: