Wednesday, June 30, 2010

Method Overloading + Techniques to shorten System.out.print()

     Tired of typing System.out.print() and System.out.println() everytime you need to print a message? Here's a technique to simplify that! I'll also discuss here this known technique in Java called Overloading.

Attachments:
  ShorterPrinting.java
  BonusClass.java

     The file above will be our reference for this example so download and take a look at 'em.
     First of all, Overloading is a technique in Java that allows us to create multiple methods with the same heading or name, but with different parameters. Take a look at the ShortPrinting class. If you will observe, you'll notice that there are a lot of methods with the name sop(), but they differ in their parameters. One accepts an argument of type String, while the other one accepts an Object of a class*. In cases where the programmer invokes the method sop() and fills the parameter with his desired argument, Java will automatically choose the appropriate method to use. Let's say I invoke the method sopln() like this:

  sopln("Some string");

  Since the parameter is of type String, then Java will invoke the method sopln(String args) instead of sopln(Object args).

So how does these methods ease my burden of having to type System.out.println() every other time?

     Apparently, if you have these methods in your class, you can just use them instead of the known System.out.print since the overloaded methods accepts any arguments. For example, if you want to print a variable x of integer type, you would normally use this:

  System.out.println(x)

  But with this technique, you can just use this:

  sopln(x)

  Java will automatically select the appropriate method to use for any invocation of the methods. Any data type can be printed using these methods, may it be a primitive data type, a String, or an Object of a class. In addition, concatenation is also allowed here. For example, you can use these methods like this:

  sop("MrUseL3tter"+" the coder.");

     Just select the equivalent method for your methods (sop() for System.out.print() and sopln() for System.out.println()).

* Since every Object of a class is a descendant of the class Object, it is allowed by Java that the argument in the methods be Object instead of a specific class.