Dev

Method overloading in the JVM




  class Calculator {
        public static void main(String… args) {
               // This method invocation will not compile
               // Yes, 1 could be float but the JVM creates it as double
               calculate(1.0);
        } 

        void calculate(float number) {}  
  }

Another common mistake is to think that the Double or any other wrapper type would be better suited to the method that is receiving a double. In fact, it takes less effort for the JVM to widen the Double wrapper to an Object instead of unboxing it to a double primitive type.

To sum up, when used directly in Java code, 1 will be int and 1.0 will be double. Widening is the laziest path to execution, boxing or unboxing comes next, and the last operation will always be varargs.

What to remember about overloading

Overloading is a very powerful technique for scenarios where you need the same method name with different parameters. It’s a useful technique because having the right name in your code makes a big difference for readability. Rather than duplicate the method and add clutter to your code, you may simply overload it. Doing this keeps your code clean and easy to read, and it reduces the risk that duplicate methods will break some part of the system.

What to keep in mind: When overloading a method the JVM will make the least effort possible; this is the order of the laziest path to execution:

  • First is widening
  • Second is boxing
  • Third is Varargs

What to watch out for: Tricky situations will arise from declaring a number directly: 1 will be int and 1.0 will be double.

Also remember that you can declare these types explicitly using the syntax of 1F or 1f for a float or 1D or 1d for a double.

That concludes our introduction to the JVM’s role in method overloading. It is important to realize that the JVM is inherently lazy, and will always follow the laziest path to execution.

Video challenge! Debugging method overloading

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video you can follow along while I debug and explain the method overloading challenge:

Learn more about Java



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.