Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

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 classes—Parent 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020