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

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 ...

Java Cloning - Copy Constructor versus Cloning

In my previous article Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example , I have discussed Java Cloning in details and answered questions about how we can use cloning to copy objects in Java, what are two different types of cloning (Shallow & Deep) and how we can implement both of them, if you haven’t read it please go ahead. In order to implement cloning, we need configure our classes to follow below steps Implement Cloneable interface in our class or its superclass or interface, Define clone() method which should handle CloneNotSupportedException (either throw or log), And in most cases from our clone() method we call the clone() method of the superclass. And super.clone() will call its super.clone() and chain will continue until call will reach to clone() method of the Object class which will create a field by field mem copy of our object and return it back. Like everything Cloning also comes with its advantages and disadvantages. However, Java c...

Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically

In any business application auditing simply means tracking and logging every change we do in the persisted records which simply means tracking every insert, update and delete operation and storing it. Auditing helps us in maintaining history records which can later help us in tracking user activities. If implemented properly auditing can also provide us similar functionality like version control systems. I have seen projects storing these things manually and doing so become very complex because you will need to write it completely by your own which will definitely require lots of code and lots of code means less maintainability and less focus on writing business logic. But why should someone need to go to this path when both JPA and Hibernate provides Automatic Auditing which we can be easily configured in your project. And here in this article, I will discuss how we can configure JPA to persist CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate columns automatically for any ...