Overload static methods in Java


It's a very normal question in the java interview question. Most of the time the interviewer asks this can we overload the static method or not & the number of time developers fails to give the correct answer.

Yes, you can overload a static method in Java. Java Method Overloading is one of the features in the OOPs concept which allows you to have two or more methods with the same method name with the difference in the parameters, in other words, we can also call this phenomenon as Compile time polymorphism.

Overloading of static method

Let's see in the below example we have an OverloadExample class which has two static test() methods which differ in the number of parameters.

 

package com.prejava;

public class OverloadExampleTest 
{
    public static void test()
    {
        System.out.println("method without parameter called");
    }
    public static void test(String name)
    {
        System.out.println("method with parameter called : "+name);
    }
    public static void main(String args[])
    {
        //Calling test() method which has no parameter
        OverloadExampleTest.test();
        
        //Calling test() method which has one parameter
        OverloadExampleTest.test("prejava");
    }
}

when we run the above code we will be getting the below output.

test() method without parameter called
test() method with parameter called : prejava

Overloading of methods which differs in static keyword

We cannot overload two methods that differ in static keyword but has the same method signature. When we try to do so we will be getting ” Cannot make a static reference to the non-static method “ error.

package com.prejava;

public class OverloadExampleDemo 
{
    public void ram()
    {
        System.out.println("Non static ram() method called");
    }
    
    public static void ram()
    {
        System.out.println("static ram() method called");
    }
    
    public static void main(String args[])
    {
        //Calling the ram() method
        OverloadExampleDemo .ram();
        
    }
}

Running the above code will lead to the below exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot make a static reference to the non-static method ram() from the type OverloadExampleDemo 

	at com.prejava.OverloadExampleDemo .main(OverloadExampleDemo .java:21)

Related Articles

post a comment