Friday, October 24, 2008

Polymorphism

Any Java object that can pass more than one IS-A test can be considered polymorphic.
Other than objects of type Object, all Java objects are polymorphic in that they pass the IS-A test for their own type and for class Object.
Remember that the only way to access an object is through a reference variable, and there are a few key things to remember about references:
  • A reference variable can be of only one type, and once declared, that type can never be changed (although the object it references can change).
  • A reference is a variable, so it can be reassigned to other objects, (unless the reference is declared final).
  • A reference variable's type determines the methods that can be invoked on the object the variable is referencing.
  • A reference variable can refer to any object of the same type as the declared reference, or—this is the big one—it can refer to any subtype of the declared type!
  • A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.
In simple terms, polymorphism is the ability of one type, A, to appear as and be used like another type, B. In strongly typed languages, this usually means that type A somehow derives from type B, or type A implements an interface that represents type B.

No comments: