Is a runtime generator or compile-time polymorphism?

I read that the following format falls under parametric polymorphism, but can we classify it at one time or at the time of run-time or compilation polymorphism?

public class Stack<T> { // items are of type T, which is known when we create the object T[] items; int count; public void Push(T item) {...} //type of method pop will be decided when we create the object public T Pop() {...} } 
+7
source share
1 answer

A bit of both. To use a generic class, you must specify a type parameter to it at compile time, but the type parameter can have an interface or a base class, so the actual specific type of objects used at run time can vary.

For example, here I have a code snippet with a Stack<T> field. I decided to use the interface as a type parameter. This uses parametric polymorphism at compile time. You must choose which type parameter your _stack field will use at compile time:

 public interface IFoo { void Foo(); } public Stack<IFoo> _stack = new Stack<IFoo>(); 

Now that this code snippet is really running, I can use any object whose class implements IFoo , and this decision does not need to be made until runtime:

 public class Foo1 : IFoo { public void Foo() { Console.WriteLine("Foo1"); } } public class Foo2 : IFoo { public void Foo() { Console.WriteLine("Foo2"); } } public class Foo3 : IFoo { public void Foo() { Console.WriteLine("Foo2"); } } _stack.Push(new Foo1()); _stack.Push(new Foo2()); _stack.Push(new Foo3()); 

This is an example of a polymorphism subtype that is used at run time.

+9
source

All Articles