How to Add Buttons and Text to Your JavaFX Project
How to Use if Statements in Java
Java: Data Sets Using Arrays and Collections

How to Overload Methods in Java

A Java class can contain two or more methods with the same name, provided that those methods accept different parameters. This technique, called overloading, is one of the keys to building flexibility into your classes. With overloading, you can anticipate different ways that someone might want to invoke an object’s functions and then provide overloaded methods for each alternative.

The term overloading is accurate but a little unfortunate. Normally, when you say that something is overloaded, there’s a problem. Fortunately, you don’t have to worry about Java collapsing under the weight of overloaded methods.

You’re already familiar with several classes that have overloaded methods, though you may not realize it. The PrintWriter class, for example (which you access via System.out), defines 10 versions of the println method that allow you to print different types of data. The following lines show the method declaration for each of these overloads:

void println()
void println(boolean x)
void println(char x)
void println(char[] x)
void println(double x)
void println(float x)
void println(int x)
void println(long x)
void println(Object x)
void println(String x)

The basic rule in creating overloaded methods is that every method must have a unique signature. A method’s signature is the combination of its name and the number and types of parameters it accepts. Thus, each of the println methods has a different signature, because although all the methods have the same name, each method accepts a different parameter type.

Two things that are not a part of a method’s signature are

  • The method’s return type: You can’t code two methods with the same name and parameters but with different return types.

  • The names of the parameters: All that matters to the method signature are the types of the parameters and the order in which they appear. Thus the following two methods have the same signature:

double someMethodOfMine(double x, boolean y)
double someMethodOfMine(double param1, boolean param2)
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Nest Java’s Enhanced For Loops
Increment and Decrement Operators in Java
JavaScript For Dummies Cheat Sheet
Programming Java: All about Generics
The gen Directory File