OOP101 in AX 2012 part 3: Polymorphism

Continue reading

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.

More articles
Explore our blog

What can we do for you?

We'd love to hear about your project. Our team will get back to you within two working days.

Thank you for inquiry, we’ve passed it to our sales department, our representative will reach you back in his earliest convenience.
Oops! Something went wrong while submitting the form.