Java ProgrammingLearn about Method Overloading in Java

Learn about Method Overloading in Java

 

In the previous article, we have talked about Method Recursion. We have supported our talks by building a Recursive Search Application. Let’s go back to that example. Suppose you want to exclude “$RECYCLE.BIN” from the list of directories you want to search in. That’s easy, you would just have to modify the search() method to make it accept a third parameter, a directory name string, and make an if condition that excludes this directory like the following:

            for (File f : filelist) {
                if (f.isDirectory() && f.getName() != exclude) {
                    search(strFile, f, exclude);
                }
            }

But now you will have to change the way you call the method in the Main() function to add the third argument:

if (objRecurser.search("readme.txt", dir, "$RECYCLE.BIN") == 1){
            System.out.println("The file was not found");
}

Everything seems to work. But what if are searching in a directory where you don’t want to exclude any directory names from? To add to the complication, the users that are working with your class are complaining that the method does not work anymore. They don’t know that they are now forced to enter an “exclude” parameter for the method to make it work again. To solve problems like those, Java introduces “method overloading”.

You overload a method when you create another one with the same name by accepting a different number of parameters, or different types of parameters. To apply this in our case, we will restore the search() method to what it was before we added the third parameter, and create a new method with the same name that handles directory exclusion. The modified code is shown below:

import java.io.File;

public class Recurser {
    public int search(String strFile, File dir){
        File[] filelist = dir.listFiles();
        if (filelist != null){
            for (File f : filelist) {
                if (f.isFile()){
                    if (f.getName().equals(strFile)) {
                        System.out.println("Found " + strFile + " in " + dir.getPath());
                        return 0;
                    }
                }
            }
            for (File f : filelist) {
                if (f.isDirectory()) {
                    search(strFile, f);
                }
            }
        }
        return 1;
    }
    
    public int search(String strFile, File dir, String exclude){
        File[] filelist = dir.listFiles();
        if (filelist != null){
            for (File f : filelist) {
                if (f.isFile()){
                    if (f.getName().equals(strFile)) {
                        System.out.println("Found " + strFile + " in " + dir.getPath());
                        return 0;
                    }
                }
            }
            for (File f : filelist) {
                if (f.isDirectory() && f.getName() != exclude) {
                    search(strFile, f, exclude);
                }
            }
        }
        return 1;
    }

Now the users of your class can call the search() method with two parameters as they used to do without raising any errors. At the same time, you can pass on “RECYCLE.BIN” as a third parameter to be excluded from search.

Java Programming Course for Beginner From Scratch

Classes Access Levels

When you are designing a class, you often use methods and attributes that are not meant to be exposed to the calling code. For example, suppose you built a user authentication class. It accepts the username and password, compares them to the stored values, and then grants or denies access accordingly. A class should look like this:

package MainClass;

public class Auth {
    String username = "johndoe";
    String password = "abc123";
    
    public Boolean authenticate(String user, String pass){
        if (user == username && password == "abc123"){
            return true;
        } 
        else {
            return false;
        }
    }
}

Then you can call it from the Main() method like this:

package MainClass;
class MainClass {

    public static void main(String[] args) {
       Auth objAuth = new Auth();
        if (objAuth.authenticate("johndoe","abc123")){
           System.out.println("Access Granted");
       }
       else {
           System.out.println("Access Denied");
        }
    }
}

Yet there is nothing that prevents me from viewing the values of those variables and logging in with the correct credentials. Even worse, I can login with my own, nonexistent credentials, by doing this:

objAuth.username = "hacker";
objAuth.password = "malicious";

Now I can use those credentials to gain access to the system. Of course in a real world application, the credentials will never be stored in the class this way, they would be pulled from a database. But the database credentials would be hardcoded in the class, which poses the same vulnerability.

To address this and other related issues, we have the class access levels. These are keywords that will limit access to the specified method or attribute as follows:

  • Public: the most lenient. A method or attribute that is declared public can be accessed from anywhere, inside or outside their package. For that reason, the Main() method is always created as public.
  • Protected: methods and attributes can be accessed from the same package (namespace) as well as from subclasses in other packages.
  • Private: methods and attributes can only be accessed from their own class.

Having known that, I can create the fields that hold the credentials like this:

private String username = "johndoe";
private String password = "abc123";

Java grants protected access level by default to class fields that do not have an access level specified.

Conclusion

In this article, we have discussed Method Overloading. Then, we learned about the access control levels that protect your class data from unwanted access.

In the next article, you will build upon access levels, and you will see how you can use them effectively to separate the interface from implementation. Then we’ll start discussing “class initialization”. See you next.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -