Tutorial

OOP101 in AX 2012 part 3: Polymorphism

OOP101 in AX 2012 part 3: Polymorphism
Published in
September 2015

Using inheritance patterns or implementing an interfaces gives us quite a few advantages, one of which is undoubtedly the property of the inclusion polymorphism.

Polymorphism comes from the Greek words polys for many and morphe for shape. Inclusion polymorphism gives us the ability to use created object from the derived class wherever we can use object from the base class. I prepared an simple job based on the configuration from the post OOP101 in AX 2012 part 1.

static void InterfacePolymorphism(Args _args)

{

   Car car123 = new Car();

   Bike bike123 = new Bike();

   void testFcn(Drivable _driv)

   {

       Car tmpCar;

       Bike tmpBike;

       _driv.moveBack();

       _driv.turnRight();

       if(_driv is Car)

       {

           tmpCar = _driv as Car;

           tmpCar.printHello();

       }

       if (_driv is Bike)

       {

           tmpBike = _driv as Bike;

           tmpBike.printHello();

       }

   }

   testFcn(bike123);

   testFcn(car123);

}

Output:

class Bike implements Drivable

{

...

public void printHello()

{

   info("I am a bike");

}

}

class Car implements Drivable

{

...

public void printHello()

{

   info("I am a car");

}

}

In this job I created a local function that takes as an argument object which implements an interface Drivable. Inside this job I call common methods like moveBack and turnRight but also after performing downcasting to derived classes I can call method specific to them like in this case printHello. As keyword is used to explicitly perform downcasting, and is on the other hand performs a type checking. When performing upcasting we do not need to use as keyword; upcasting can be done implicitly. The same job could be created for the inheritance configuration from OOP101 in AX 2012 part 2. By the means of polymorphism we can detach ourselves from the implementation of a given object and program for the given interface which is a great power that can significantly increase the productivity, especially when working on the big projects.

Written by
Andrzej Lapinski

Student at the Wroclaw University of Technology. Passionate about science and technology. Main areas of interest are probability theory and machine learning. Currently I am working with X++ and Microsoft Dynamics.