Program 7.1: Polymorphic Website Constructors

Polymorphism can be implemented in programmer-defined classes as well. To do this simply write two methods with the same name but different argument lists. For instance the last chapter had two different versions of the website constructor, one that took three arguments and one that took no arguments. You can use both of these in a single class.

public class website {

  String name;
  String url;
  String description;
  public website(String n, String u, String d) {
    name = n; 
    url  = u;
    description = d;

  public website() {
    name = ""; 
    url  = "";
    description = "";

Normally a single identifier refers to exactly one method. When as above, one identifier refers to more than one method, the method is overloaded. You could argue that this should be called identifier overloading rather than method overloading since itıs the identifier that refers to more than one method, not the method that refers to more than one identifier. However in common usage this is called method overloading.

Which method an identifier refers to depends on the signature. The signature is the number, type, and order of the arguments passed to a method. The signature of the first constructor in Program 7.1 is three Strings. The signature of the second method is no arguments of any type. Thus the first version of the website constructor is called when there are three String arguments and the second version is used when there arenıt any arguments.

If there are one, two, four or more String arguments to the constructor, or arguments that aren't Strings, then the compiler generates an error because it doesn't have a method whose signature matches the requested method call. For example

Error:    Method website(double) not found in class website.  line 17    
Many of the system supplied methods are polymorphic. For instance println can print a String, an int, or many other kinds of data types. The compiler is responsible for determining what is being passed to the println method and calling the right variant of the method accordingly.

Copyright 1996 Elliotte Rusty Harold
This Chapter