7.4 Polymorphism
Polymorphism is Greek for "many shapes." There are two main aspects of Java that make the language polymorphic: overloading and overriding. They both define different ways of referring to the different methods that use the same name. This sounds rather complicated, but it is really rather straightforward.
Java is not the only language that implements polymorphism. This is an aspect of numerous object-oriented languages. The concepts are difficult to explain without reference to other advanced concepts we have not covered yet. So if you find this a bit confusing, try the examples and keep reading, and then reread this section later.
7.4.1 Overloading
Overloading a method means using the same name for more than one method in the same class, supplying each with different argument lists. For example, here are some overloaded methods of the String class:
compareTo(Object o) // compares this String to another Object compareTo(String anotherString) // compares two Strings // lexigraphically
Overloading is an important concept in Java and is similar to behavior implicit in ColdFusion functions. Consider a familiar function, such as ListGetAt(), which returns the element in a given position in a list. When invoking this function, you can choose to send it as two parameters or three:
ListGetAt(list, position [, delimiters])
The delimiters argument is optional. If you do not supply an explicit value for it, the function assumes the delimiter to be a comma. While the implementation of this code is hidden from ColdFusion developers, the result is similar.
Of course, to the ColdFusion developer, there is only one ListGetAt() function, and it has three arguments, one of which is optional. But the implementation of that method is totally shielded from the developer. If you wanted to achieve the same effect in Java, you would use overloaded methods. That is, your List class would contain two methods, overloaded (something like this):
ListGetAt(String list, int position) { ...//def here }
and
ListGetAt(String list, int position, char delims) { ...// def here }
Then Java will use the correct method based on the argument list sent it. If a method is invoked with an argument list that does not match any of your method definition's argument list, a NoClassDefFoundError exception is thrown.
NOTE
As long as we've brought it up, the Java API has numerous built-in methods for manipulating strings, finding characters, and so on. Java data types are obviously different from those in ColdFusion. While Java does have arrays like ColdFusion does, what about the lists and structures? Lists in Java are in the Collections API (java.util). Structures don't exist per se, but name-value paired data is worked with in many different ways in Java, including vectors, hash tables, Maps, properties, and more. These are all in java.util as well if you're eager to peek. Don't worry about running out of ways to store name-value pairs in Java. We will talk about all of these in Chapter 11, "Collections and Regular Expressions."
It is perfectly legal to specify a different return type for overloaded methods. Specifying a different return type for a method is not sufficient to make it overloaded. You must also specify a different argument list.
Here is a more complete example of overloading:
7.4.2 DemoOverload.java
package chp7; public class DemoOverload { public int getIt(int i) { return i; } // overloads getIt method public String getIt(int i, String s) { String y = Integer.toString(i) + " " + s; return y; } public static void main(String[] a) { int x = 10; DemoOverload o = new DemoOverload(); // prints 10 System.out.println(o.getIt(x)); System.out.println(o.getIt(x, " is a good number")); } }
You can compile and run this example. Add your own methods, and change the definitions of these methods to get used to working with overloading. There are numerous examples of overloading in the Java API. For instance, the compareTo() method of the Integer wrapper class is overloaded:
public int compareTo(Integer anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1)); }
This compares two objects numerically. The version shown below accepts an object, and throws a ClassCastException if the value passed is not of type Integer.
public int compareTo(Object o) { return compareTo((Integer)o); }
Let's drop these into a class and see how they behave:
7.4.3 Overload2.java
package chp7; /* demos overloading using API methods * Integer.valueOf(). * The first method returns the integer passed. * The second returns the int in the radix passed. */ public class Overload2 { public static void main(String[] ar) { String s = "100"; int r = 2; Overload2 o = new Overload2(); System.out.println("The int: " + Integer.valueOf(s)); System.out.println("The int in base " + r + ": " + Integer.valueOf(s, r)); } // end main }// eof
Overload2 prints the following:
The int: 100 The int in base 2: 4
7.4.4 Overriding
There is another aspect to polymorphism: overriding. We have mentioned inheritance, and we will talk about it in more depth later in this chapter. When a method is inherited from a superclass, the subclass can change the implementation of that method. The act of a subclass redefining the implementation of a method it has inherited from a superclass is called method overriding.
In the case of an abstract class (which we'll also talk about at the end of this chapter), the subclass must define the implementation of the method. The main difference between an overloaded method and an overridden method is that overriding does not allow you to change the return type.
Here is an example of method overriding. This example defines two classesParent and Child. The Parent class defines a simple string s, and it defines one method for retrieving that string, getS(). The Child class also defines a getS() method, therefore overriding the Parent class's getS(). They have the same name, but they do different things.
7.4.5 Parent.java
package chp7; // Parent is superclass of Child // it just defines a string and an access method, getS() public class Parent { String s = "I am Darth Vader (Parent). "; String getS() { return s; } }
7.4.6 Child.java
package chp7; /** * demonstrates overridding * the getS() method of Parent */ // "extends" means that Child inherits from // the Parent class public class Child extends Parent { // this value is part of the Child class String s; // overrides Parent's method String getS() { // the "super" keyword calls the parent // of current class. That is, "super" // refers to the value after the "extends" // keyword s = super.s + " I am Luke (child). "; return s; } public static void main(String [] ar) { // make a new baby Child luke = new Child(); // call the Child's overriding method System.out.println(luke.getS()); } }
Here is the output of running Child:
I am Darth Vader (Parent). I am Luke (child).
NOTE
These listings honor Ray Camden's custom tag example using these same characters in his book Mastering ColdFusion. If you have written nested custom tags in ColdFusion, you may find it easier conceptually to understand working with inheritance in Java.
Overloading occurs in the compiler at compile time. The compiler chooses which one you mean by finding the corresponding argument type to what you called for. By contrast, overriding occurs at runtime. It happens when one class extends another, and the subclass has a method with the same signature as a method of the superclass.
You will never see static methods associated with overriding. That's because you use overriding when an object could belong to a certain class or a subclass of it. Because static methods do not deal directly with objects, the runtime doesn't have to bother trying to sort out which method is meant to be invoked.
7.4.7 private Methods
private methods can be called only from methods in the same class. It is common for us to define private data and then define public methods to set or access that data. While most methods are public, it is not uncommon to find private methods.
private methods are useful when you want to break up functionality into multiple methods. Maybe you need a helper to perform certain operations, and the public would not be able to call the helper by itself coherently.
All you need to do to create a private method is to exchange the keyword public for private in the method definition, like this:
private doSomething(int a) { ...// code here }
The chief reason to define a method as private is that the programmer can be assured that nothing outside the defining class is accessing it. That means you can drop it or change it without worrying about what you might break somewhere else. You don't have that assurance with a public method.