Saturday, October 25, 2008

Section 1.5: Polymorphism

Requirement: Describe polymorphism as it applies to classes and interfaces, and describe and apply the "program to an interface" principle.


Polymorphism:

(1.5.1) Polymorphism is the fact that an object variable can refer to multiple actual types. (1.5.2) The is-a rule states that every object of a subclass is an object of the superclass. (1.5.3) You can assign a subclass reference to a superclass variable (ex: assuming that Employee is the superclass and Manager is the subclass you can write: Employee e = new Manager(...) but you cannot write: Manager m = new Employee(....), all managers are employees but not all employees are managers). (1.5.4) Arrays of subclass references can refer to arrays of superclass references without a cast:

Ex:
Manager[] managers = new Manager[10];
Employee[] staff = managers; //This is OK

But the caution here is that managers and staff are references for the same array. So if you write something like: staff[0] = new Employee(....); the compiler will not indicate any errors. But what you have done actually is that you assigned an Employee object to a Manager reference since managers[0] is the same as staff[0] which is illegal. So if you try to something like that an ArrayStoreException will be caused at run time.


Program to an Interface Principle:
(from the JavaRanch forum)

(1.5.5) Program to an interface means don't tie relationships to classes, instead tie them to interfaces. For example, I have a class C1 which is a parameter for a method M2 in class C2, I code M2 method as M2(C1 c). I cannot use M2 to process any objects from classes other than C1. Instead if an interface I1 is created and which is implemented by C1, I can change the method signature to M2(I1 i) and this will be able to process objects of any class that implements I1 including C1 instead of exclusively processing C1 objects.

No comments: