Skip to main content

Why Should We Follow Method Overloading Rules

In my previous articles, Everything About Method Overloading Vs Method Overriding and How Does JVM Handle Method Overloading and Overriding Internally, I have discussed what is method overloading and overriding, how both are different than each other, How JVM handles them internally and what rules we should follow in order to implement these concepts.

In order to overload or override a method we need to follow certain rules, some of them are mandatory while others are optional and to become a good programmer we should always try to understand the reason behind these rules.

I am going to write two articles where I will try to look into the method overloading and overriding rules and try to figure out why we need to follow them.

In this article, we will see what rules we should follow to overload a method and we will also try to know why we should follow these rules.

Method Overloading

In general, method overloading means reusing same method name to define more than one method but all methods must have a different argument list.

We can take the example of the print method present in PrintStream class which gets called when we call System.out.print() to print something. By calling this method on several data types it seems like there is just one print method which is accepting all types and printing their values.

But actually, there are 9 different print methods as shown in below image

method-overloading

Well, the PrintStream class creator could have created methods like printBoolean or printInt or printFloat, but the idea behind naming all the 9 methods same is to let the user think that there is only one method which is printing whatever we pass to it.

Which sounds like polymorphism but as discussed in the article How Does JVM Handle Method Overloading and Overriding Internally that how method overloading get resolved at compile time, some people also term method overloading as compile-time polymorphism.

Method Overloading Rules

While defining a method we need to provide it a proper method signature which includes access specifier, return type, method name, argument list, exceptions method might throw. Based on these five things method overloading has some mandatory rules and some optional rules, which we are going to see below.

Mandatory Rules

  • Overloaded methods must have same method name: Having the same name let us reuse the same method name for different purposes and let the user believe that there is only one method which is accepting different kinds of input and doing the work according to the input.
  • Overloaded methods must have different argument lists: Since all overloaded methods must have the same name, having a different argument list becomes necessary because it is the only way to differentiate the methods from each other. Java compiler differentiates a method from other based on its method name and argument list, So different argument list helps the compiler to differentiate and recognize methods from each other so the compiler will know which method is getting called at compile time only.

Optional Rules

The compiler knows that at the time of method calling JVM needs to know the method name and JVM will pass some arguments to that method so it must also know the argument list. While other method signature elements e.g. return type, access modifier, the exception method throwing also matter but at the time of method call they become optional.

So the different argument list is sufficient for the compiler to differentiate between the methods even if they have the same name so rules mentioned below are optional and we are free to follow or not follow them. Going with below rules totally depends on your requirements and they are there to just provide us additional functionality.
  • Overloaded methods can have different return types: Return type matters when the method call is finished and JVM assigning back the value returned by that method call to some variable. But it is not required while calling the method and JVM cannot use it to differentiate between methods based on just return type. So we can either return the same as the overloaded method did or return something different or return nothing.
  • Overloaded methods can have different access modifiers: If a method is getting called by the JVM it means it has passed the compilation phase because executing the bytecode which is already compiled. So access specifier of a method is useful for the compiler but it is useless for JVM and JVM cannot differentiate between methods based on access modifier. So an overloading method can have any access modifier and we can use it according to our need.
  • Overloaded methods can throw different checked or unchecked exceptions: Again what exceptions a method might throw cannot differentiate a method from another method.And also overloaded methods are different from each other but usually, they perform the same operation on different data set and in order to do so overloaded methods may do some different operation as well which may throw a different exception.
You can find complete code on this Github Repository and please feel free to provide your valuable feedback.

Comments

Popular posts from this blog

AutoWiring Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners

In my previous article JPA Auditing: Persisting Audit Logs Automatically using EntityListeners , I have discussed how we can use Spring Data JPA automate Auditing and automatically create audit logs or history records and update CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties. So in order to save history records for our File entity, we were trying to auto-wire EntityManager inside our FileEntityListener class and we have come to know that we can not do this. We can not inject any Spring-managed bean in the EntityListener because EntityListeners are instantiated by JPA before Spring inject anything into it. EntityListeners are not managed Spring so Spring cannot inject any Spring-managed bean e.g. EntityManager in the EntityListeners. And this case is not just with EntityListeners, you can not auto wire any Spring-managed bean into another class (i.e. utility classes) which is not managed by Spring. Because it is a very common problem and can also arise with other c

Why Single Java Source File Can Not Have More Than One public class

According to Java standards and common practices we should declare every class in its own source file. And even if we declare multiple classes in the single source file (.java) still each class will have its own class file after compilation. But the fact is that we can declare more than one class in a single source file with below constraints, Each source file should contain only one public class and the name of that public class should be similar to the name of the source file. If you are declaring the main method in your source file then main should lie in that public class If there is no public class in the source file then main method can lie in any class and we can give any name to the source file. If you are not following 1st constraint then you will receive a compilation error saying “ The public type A must be defined in its own file ”.  While if you are not following the second constraint you will receive an error “ Error: Could not find or load main class User ” after exec

How Does JVM Handle Method Overloading and Overriding Internally

In my previous article Everything About Method Overloading Vs Method Overriding , I have discussed method overloading and overriding, their rules and differences. In this article, we will see How Does JVM Handle Method Overloading And Overriding Internally, how JVM identifies which method should get called. Let’s take the example of parent class  Mammal and a child  Human classes from our previous blog to understand it more clearly. public class OverridingInternalExample { private static class Mammal { public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); } } private static class Human extends Mammal { @Override public void speak() { System.out.println("Hello"); } // Valid overload of speak public void speak(String language) { if (language.equals("Hindi")) System.out.println("Namaste"); else System.out.println("Hello"); } @