Java Reference
In-Depth Information
double m = x.getMeasure();
can call different methods depending on the momentary contents of x .
Polymorphism denotes the principle that behavior can vary depending on the
actual type of an object.
The principle that the actual type of the object determines the method to be called is
called polymorphism. The term Ȓpolymorphismȓ comes from the Greek words for
Ȓmany shapesȓ. The same computation works for objects of many shapes, and adapts
itself to the nature of the objects. In Java, all instance methods are polymorphic.
When you see a polymorphic method call, such as x.getMeasure() , there are
several possible getMeasure methods that can be called. You have already seen
another case in which the same method name can refer to different methods, namely
when a method name is overloaded: that is, when a single class has several methods
with the same name but different parameter types. For example, you can have two
constructors BankAccount() and BankAccount(double) . The compiler
selects the appropriate method when compiling the program, simply by looking at the
types of the parameters:
account = new BankAccount();
// Compiler selects BankAccount()
account = new BankAccount(10000);
// Compiler selects BankAccount(double)
397
398
There is an important difference between polymorphism and overloading. The
compiler picks an overloaded method when translating the program, before the
program ever runs. This method selection is called early binding. However, when
selecting the appropriate getMeasure method in a call x.getMeasure() , the
compiler does not make any decision when translating the method. The program has
to run before anyone can know what is stored in x . Therefore, the virtual machine,
and not the compiler, selects the appropriate method. This method selection is called
late binding.
Search WWH ::




Custom Search