Java programming: overloaded methods
The tutor explores the concept of overloaded methods in Java.
A class can have variables and methods. Perhaps surprisingly, it can have more than one method with the same name. Said methods will have different parameter lists. The compiler will choose the method that makes sense based on the call.
Consider, for example, this very simple class:
public class Messager{
public void tellMessage(){
System.out.println(“My message to you is Cheers!”);
}
public void tellMessage(String mess){
System.out.println(“My message to you is “+mess);
}
}
Notice the two tellMessage methods: the first expects no parameters, while the second expects a string.
One could write a driver class, such as the following, to test the overloaded method in the class Messager:
class MessagerDriver{
public static void main(String[] args){
Messager m = new Messager();
if (args.length>0){
m.tellMessage(args[0]);
}
else{
m.tellMessage();
}
}//end main
}//end Driver
After compiling, one could run MessagerDriver both with and without a command line argument, then notice the different versions of tellMessage being invoked.
For those who aren’t yet comfortable with the nuts and bolts of compiling and running a Java program: I hope to give some tips next post.
HTH:)
Source:
Niemeyer, Patrick and Jonathan Knudsen. Learning Java. Sebastopol, CA: O’Reilly Media, Inc., 2005.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.