Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are static and non static overloads each other

Does these two function overloads

class yogi{

   public static void fun(){
    System.out.println("Fun");
   }    

   public void fun(int a,int b){
    System.out.println("int");
   }

}
like image 907
dead programmer Avatar asked Jan 09 '23 14:01

dead programmer


1 Answers

Yes, those are overloads. From JLS 8.4.9:

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

It's fairly rare (IMO) for it to be a good idea to have the same name for both static and instance methods, but it's entirely valid.

Interestingly, this can cause problems in overload resolution, in that instance methods are included even when there's no instance to call the method on. For example:

public class Test {
    public void foo(String x) {
    }

    public static void foo(Object x) {
    }

    public static void bar() {
        foo(""); // Error
    }
}

The spec could have been designed so that this would be fine (and call the static method) but instead it's an error:

Test.java:9: error: non-static method foo(String) cannot be referenced
                    from a static context
        foo("");
        ^
like image 165
Jon Skeet Avatar answered Jan 17 '23 04:01

Jon Skeet