Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Object-oriented language basics, Part 7

Object-oriented language basics, Part 7

Tutorial Details:

Object-oriented language basics, Part 7
Object-oriented language basics, Part 7
By: By Jeff Friesen
Learn about Java's many shapes and find out how to accommodate generalities in your class hierarchies
olymorphism, a fundamental object-oriented programming principle, tends to confuse novice Java developers. Part of the bewilderment stems from the fact that, although there are four types of polymorphism, Java officially supports only three of them (at the moment). This article attempts to clear away the clouds surrounding polymorphism by exploring each polymorphism type -- with emphasis on the inclusion polymorphism category.
After discussing polymorphism, I turn to abstract classes and abstract methods. Abstract classes prevent developers from creating objects out of those classes that represent generic concepts. In addition, abstract classes often work with inclusion polymorphism. Though abstract classes and interfaces do resemble one another, they also differ, and I will explain how in this article.
If you follow the Java 101 column, you know that we are currently touring Java's object-oriented language basics. So far, this series has covered class declaration, object creation, field/method declaration and access, object composition, object layering, multiple implementation inheritance, the root of all classes, and interfaces (with multiple interface inheritance). In addition, I have introduced the specialized topics of enumerated types and singletons. Read the whole series on object-oriented language basics, and learn what it means for a Java program to be object oriented:
Part 1: Learn how to declare classes and create objects
Part 2: Declare and access fields and methods
Part 3: Composition: Build objects from other objects
Part 4: Inheritance: Build objects in layers
Part 5: The root of all classes
Part 6: Use interfaces for safe multiple inheritance and a great deal more
Part 7: Learn about Java's many shapes and find out how to accommodate generalities in your class hierarchies
Polymorphism
The quality or state of assuming different forms, or shapes, is known as polymorphism. Water provides a good real-world example of polymorphism. When frozen, water turns into ice. When that ice melts, a liquid appears. Boil that liquid and you end up with a gas. Computer languages also manifest polymorphism in different ways. As Wm. Paul Rogers points out in his excellent article " Reveal the Magic Behind Subtype Polymorphism ," there are four kinds of polymorphism at the computer-language level: coercion, overloading, parametric, and inclusion.
Coercion polymorphism refers to a single operation serving several types through implicit type conversion. For example, the subtraction operation manifests itself in source code through the subtraction operator ( - ). That operator allows you to subtract an integer from another integer and a floating-point value from another floating-point value. However, if one operand is an integer and the other operand a floating-point value, the compiler must convert the integer's operand type to floating-point. Otherwise, a type error occurs -- because Java's subtraction operation does not subtract integers from floating-point values, or vice versa. Another example of coercion polymorphism involves method calls. If a subclass declares a method with a superclass parameter, and if a call is made to that method with a subclass object reference, the compiler implicitly converts the subclass reference type to the superclass reference type. That way, only superclass-defined operations are legal (without explicit type casts) in the method.
Overloading polymorphism refers to using a single identifier for different operations. For example, the + identifier -- I use the term identifier in a general sense -- signifies any one of several operations based on its operands' types. If both operands have integer types, the integer addition operation occurs. Similarly, if both operands have floating-point types, a floating-point operation occurs. Finally, if those operands are strings, string concatenation is guaranteed to be the operation.
Along with its language-defined operator overloading, Java also permits method names to overload -- as long as the number and/or types of each method's parameters differ. That way, the same method-name identifier can apply to different operations.
Many developers do not regard the coercion and overloading polymorphism categories as true forms of polymorphism. At close inspection, coercion and overloading are seen as convenient type conversion aids and syntactic sugar. In contrast, parametric and inclusion polymorphism are considered genuine polymorphism.
Parametric polymorphism refers to a class declaration that allows the same field names and method signatures to associate with a different type in each instance of that class. For example, you might create a LinkedList class with a data field that holds any type of data. To allow for proper type checking at compile time, you do not want to give that field Object type (as in Object data; ) as the compiler cannot inform you if the code attempts to perform invalid operations on data , because only the JVM knows the actual type of data at runtime. However, you do not want to tie data to a specific type in your source code, because you lose the benefit of being able to store different object types in your LinkedList objects. To achieve the best of both worlds, parametric polymorphism gives you the benefits of static type checking -- which alerts you to attempts that perform invalid operations on data -- and allows data to hold different object types. Probably the best-known example of parametric polymorphism is the C++ template language feature. Although Java does not officially support parametric polymorphism, developers expect Sun to add that support to version 1.5 of the SDK, which is scheduled for a 2003 release. For more information on parametric polymorphism, I refer you to Eric Allen's well-written article " Behold the Power of Parametric Polymorphism ."
Inclusion polymorphism refers to a situation in which a type can be another type's subtype. Every subtype value can appear in a supertype context, where the execution of the supertype's operations (on that value) results in the execution of the subtype's equivalent operations. For that reason, inclusion polymorphism is also known as subtype polymorphism. To understand inclusion (or subtype) polymorphism, you must understand how Java binds method calls to classes and objects.
Method binding
Recall from an earlier article in this series that Java supports two categories of methods: class (also known as static) and instance (also known as nonstatic). Class methods associate with classes, and instance methods associate with objects. When you call a method, Java binds that method call to either a class or an object, depending on that method's category.
Listing 1 shows how Java statically binds class method calls to classes at compile time:
Listing 1. SMB.java
// SMB.java
class Superclass
{
static void method ()
{
System.out.println ("Superclass method");
}
}
class Subclass extends Superclass
{
static void method ()
{
System.out.println ("Subclass method");
}
}
class SMB
{
public static void main (String [] args)
{
Superclass sc = new Superclass ();
sc.method ();
sc = new Subclass ();
sc.method ();
}
}
SMB declares a class hierarchy consisting of Superclass and Subclass classes. Each of those classes declares a class method named method() . A third class, SMB , declares a main() method that does the following:
Creates a Superclass object
Assigns that object's reference to sc
Calls method() by (apparently) using sc 's reference
Creates a Subclass object
Assigns that object's reference to sc
Calls method() by (apparently) using sc 's reference
When run, SMB produces the following output:
Superclass method
Superclass method
The output might surprise you, but remember that class methods associate with classes, not objects. Even though SMB 's sc.method() calls give the impression that main() calls instance methods, main() calls only a single method() statically bound to Superclass . SMB 's main() method could just as easily achieve the same output by replacing main() 's code with two consecutive Superclass.method (); calls. As a result, inclusion/subtype polymorphism does not exist with statically bound method calls. ( Note: Calling class methods via object reference variables is not wise because it clouds the fact that those methods are class methods.)
Contrary to how Java treats class methods, Java dynamically binds instance method calls to objects at runtime, making inclusion/subtype polymorphism possible. Listing 2 demonstrates this:
Listing 2. DMB1.java
// DMB1.java
class Superclass
{
void method ()
{
System.out.println ("Superclass method");
}
}
class Subclass extends Superclass
{
void method ()
{
System.out.println ("Subclass method");
}
}
class DMB1
{
public static void main (String [] args)
{
Superclass sc = new Superclass ();
sc.method ();
sc = new Subclass ();
sc.method ();
}
}
DMB1 's source code is nearly identical to SMB 's source code. Apart from its class name, DMB1 only differs in the absence of the static keyword from the method() signatures in Superclass and Subclass . When run, DMB1 outputs the following:
Superclass method
Subclass method
DMB1 's output differs from SMB1 's because the JVM dynamically locates the correct method() to call based on the object reference appearing in sc . In the first method() call, the JVM uses the Superclass object reference it retrieved from sc to locate Superclass 's method() . In the second method() call, the JVM uses the Subclass object reference it retrieved from sc to locate Subclass 's method() . And that is inclusion/subtype polymorphism at work.
Because Java dynamically binds instance method calls to objects at runtime, you


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Object-oriented language basics, Part 7

View Tutorial:
Object-oriented language basics, Part 7

Related Tutorials:

Programming Java threads in the real world, Part 3 - JavaWorld - November 1998
Programming Java threads in the real world, Part 3 - JavaWorld - November 1998
 
Programming Java threads in the real world, Part 8
Programming Java threads in the real world, Part 8
 
Use JNDI to share objects between different virtual machines - JavaWorld July 1999
Use JNDI to share objects between different virtual machines - JavaWorld July 1999
 
Problems with Swing's new XMLOutputStream class - JavaWorld August 1999
Problems with Swing's new XMLOutputStream class - JavaWorld August 1999
 
Master Java with these introductory books - JavaWorld May 2001
Master Java with these introductory books - JavaWorld May 2001
 
Object-oriented language basics, Part 7
Object-oriented language basics, Part 7
 
Good introduction to JDO
Good introduction to JDO
 
How to build an interpreter in Java, Part 1: The BASICs (JavaWorld / May 1997 / by Chuck McManis)
How to build an interpreter in Java, Part 1: The BASICs (JavaWorld / May 1997 / by Chuck McManis)
 
Datastructures and algorithms, Part 1
Datastructures and algorithms, Part 1
 
Impressive !
Impressive !
 
Good, but obsolete
Good, but obsolete
 
Very interesting
Very interesting
 
Maybe the future UI design of choice
Maybe the future UI design of choice
 
Introducory article
Introducory article
 
Lisp and Java
Lisp and Java In this article, we\'re going to steal an idea from one of the most theft-worthy languages out there: Lisp. We\'re going to pick out one of its most useful features -- the ability to treat functions as data -- and talk about how to apply th
 
JDBC scripting, Part 2
JDBC scripting, Part 2 Programming and Java scripting in JudoScript Summary JudoScript is a rich functional scripting language, and an easy and powerful general programming and Java scripting language. JudoScript's power comes from its synergy of
 
Drools
Drools is an augmented implementation of Forgy's Rete algorithm tailored for the Java language. Adapting Rete to an object-oriented interface allows for more natural expression of business rules with regards to business objects.
 
An Introduction to Java Object Persistence with EJB
The 'impedance mismatch' between relational databases' tabular orientation and object-oriented Java's hierarchical one is a perennial problem for which the Java world has several good solution offerings. This article, the first in a three-part series, wil
 
Object-Oriented Language: Java / APIs (Classes & Libraries)
The Java Platform APIs are a set of essential interfaces that developers need to build their Java applications and applets. All Java Platfrom APIs are open and extensible, and are created by JavaSoft and industry-wide specialists in each target technology
 
Java RMI Tutorial
This is a brief introduction to Java Remote Method Invocation (RMI). Java RMI is a mechanism that allows one to invoke a method on an object that exists in another address space.The other address space could be on the same machine or a different one. The
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.