Java Reference
In-Depth Information
Consider the following snippet of code that shows a definition of a square() method, which accepts a parameter
of double data type:
double square(double num) {
return num * num;
}
The square() method can be called with actual parameter of double data type as
double d1 = 20.23;
double result = square(d1);
The same square() method may also be called with actual parameter of int data type as
int k = 20;
double result = square(k);
You have just seen that the square() method works on double data type as well as int data type although you
have defined it only once in terms of a formal parameter of double data type. This is exactly what polymorphism
means. In this case, the square() method is called a polymorphic method with respect to double and int data type.
Thus the square() method is exhibiting polymorphic behavior even though the programmer who wrote the code
did not intend it. The square() method is polymorphic because of the implicit type conversion (coercion from int to
double ) provided by Java language. Here is a more formal definition of a polymorphic method:
Suppose m is a method that declares a formal parameter of type T. If S is a type that can be implicitly
converted to T, the method m is said to be polymorphic with respect to S and T.
Inclusion Polymorphism
Inclusion is a universal polymorphism. It is also known as subtype (or subclass) polymorphism because it is achieved
using subtyping or subclassing. This is the most common type of polymorphism supported by object-oriented
programming languages. Java supports it. Inclusion polymorphism occurs when a piece of code that is written using
a type works for all its subtypes. This type of polymorphism is possible based on the subtyping rule that a value that
belongs to a subtype also belongs to the supertype. Suppose T is a type and S1 , S2 , S3... are subtypes of T . A value that
belongs to S1 , S2 , S3... also belongs to T . This subtyping rule makes us write code as follows:
T t;
S1 s1;
S2 s2;
...
t = s1; // A value of type s1 can be assigned to variable of type T
t = s2; // A value of type s2 can be assigned to variable of type T
 
Search WWH ::




Custom Search