1.5: Fundamental Object-Oriented Concepts

1.5 Describe polymorphism as it appplies to classes and interfaces, and describe and apply the "program to an interface" principle.

Polymorphism word originates from Greeks which simply means many forms. In Java context, polymorphism means 1 object can take the place of an object of different type.

Polymorphism via Class Inheritance occurs when a certain object type is required and an object of that type or its inherited object is accepted in its place. In this case, polymorphism utilizes the is-a relationship. A subclass is said to have an is-a relationship with its superclass. When an object is polymorphically acting as another object, the more specific object is restricted to only using the public interface of the more general object. The is-a relationship is unidirectional, ie., only the subclass can take the place of its superclass.

Polymorphism via Interfaces occurs when a class implements an interface, it is required to implement all the methods in the interface. Hence, the class includes all the functionalities that the interface defines. This allows all objects instantiated from the classes to polymorphically behave as the data type of the interface.

Programming to an interface concept specifies that the code should interact based on a defined set of functionality instead of an explicitly defined object type. In other words, it is better for the public interfaces of objects to use data types that are defined as interfaces than to a particular class. This allows code to be more abstract and flexible.

0 comments:

Post a Comment