Polymorphism

 

Polymorphism

After overriding a super class method in a sub class, casting and running the super class method through the super class reference is polymorphism. Simply put, the process of calling the sub class method from the super class reference using the 3 concepts of overriding, inheritance, and casting can be described as polymorphism.

Figure 1: Polymorphism Example

As shown in this simple example, the subclass method is called by both upcasting and downcasting.

Figure 2: Polymorphism Example

This code creates an "Employee" superclass and two subclasses, "Manager" and "Programmer". The "Employee" superclass has a single method called "work" that simply prints out "The employee works". Both "Manager" and "Programmer" are subclasses of "Employee" and they override the "work" method with their respective tasks.

The "Manager" subclass has an additional method called "approvePayroll" that prints out "The manager approves payroll", and the "Programmer" subclass has an additional method called "debugCode" that prints out "The programmer debugs code".

In the "TestC" class, we create three "Employee" objects: one "Employee", one "Manager", and one "Programmer". We then upcast the "Manager" and "Programmer" objects to their respective "Employee" references. This demonstrates polymorphism, where objects of different subclasses can be treated as instances of their superclass. We then downcast the "Manager" and "Programmer" objects to their respective class references, "Manager" and "Programmer", and call their additional methods.

This output demonstrates that the "work" method is polymorphic, with each subclass executing their respective "work" methods, and that the downcasting of the "Manager" and "Programmer" objects allows us to call their additional methods specific to their class.

Comments

Popular posts from this blog

Java Standards, Class & Object

Super Keyword