Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Derived class as a parameter to a method when the parameter type is base class

Tags:

c#

inheritance

I am a newbie and trying to understand concepts of inheritance and design patterns.

I came across this pattern http://en.wikipedia.org/wiki/Strategy_pattern when I was going through some blog.

I found it interesting and wanted to learn more. So I developed the following program.

static void Main(string[] args) {     Context context;      // Three contexts following different strategies     context = new Context(new ConcreteStrategyAdd());     int resultA = context.executeStrategy(3, 4);      context = new Context(new ConcreteStrategySubtract());     int resultB = context.executeStrategy(3, 4);      context = new Context(new ConcreteStrategyMultiply());     int resultC = context.executeStrategy(3, 4);      Console.Read(); }        abstract class Strategy {     public abstract int execute(int a, int b);      public void Test()     {         Console.Write("tttt");     } }  class ConcreteStrategyAdd : Strategy {     public override int execute(int a, int b)     {         Console.WriteLine("Called ConcreteStrategyAdd's execute()");         return a + b;  // Do an addition with a and b     } }  class ConcreteStrategySubtract : Strategy {      public override int execute(int a, int b)     {         Console.WriteLine("Called ConcreteStrategySubtract's execute()");         return a - b;  // Do a subtraction with a and b     } }  class ConcreteStrategyMultiply : Strategy {     public override int execute(int a, int b)     {         Console.WriteLine("Called ConcreteStrategyMultiply's execute()");         return a * b;   // Do a multiplication with a and b     } }  class Context {     private Strategy strategy;      // Constructor     public Context(Strategy strategy)     {         this.strategy = strategy;     }      public int executeStrategy(int a, int b)     {         return strategy.execute(a, b);     } } 

The program compiles fine and is working. But my question is how is it possible to pass derived class as a parameter when the Context constructor is expecting base class as a parameter? Is the casting happening implicitly? Why does the compiler does not error?

context = new Context(new ConcreteStrategyAdd());    public Context(Strategy strategy) {     this.strategy = strategy; } 
like image 485
Sandeep Avatar asked Jan 04 '11 15:01

Sandeep


People also ask

How do you pass parameter to a base class from a derived class in Java?

To pass arguments to a constructor in a base class, use an expanded form of the derived class' constructor declaration, which passes arguments along to one or more base class constructors. Here, base1 through baseN are the names of the base classes inherited by the derived class.

Can be inherited by a derived class from a base class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

Can you assign a derived class object to a base class object?

Object Slicing in C++ In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Can you cast a base class to a derived class?

Likewise, a reference to base class can be converted to a reference to derived class using static_cast . If the source type is polymorphic, dynamic_cast can be used to perform a base to derived conversion.


Video Answer


2 Answers

Put really simply:

A Derived class (or subclass) is an instance of its base class.

So, when you pass an instance of ConcreteStrategyAdd into the constructor, you are essentially passing a Strategy object in.

There is no casting involved. The type hierarchy allows for this type of programming. It allows programmers to use polymorphism in their code.

like image 64
jjnguy Avatar answered Sep 29 '22 11:09

jjnguy


There is no casting needed, since ConcreteStrategyAdd is a Strategy - it satisfies all the requirements of being a Strategy. This is the principle of Polymorphism.

Perhaps a more simplistic example is needed:

abstract class Fruit { }  class Apple : Fruit { } class Orange : Fruit { } class Melon : Fruit { }  class FruitBasket {     void Add(Fruit item) { ... } }  FruitBasket basket = new FruitBasket(); basket.Add(new Apple()); // Apple IS A fruit basket.Add(new Orange()); // Orange IS A fruit basket.Add(new Melon()); // Melon IS A fruit  class Potato : Vegetable { }  basket.Add(new Potato()); // ERROR! Potato IS NOT A fruit. 
like image 43
MattDavey Avatar answered Sep 29 '22 10:09

MattDavey