Java – static and non static overloads to each other

Are these two functions overloaded

class yogi{

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

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

}

Solution

Yes, those are overloads From JLS 8.4 9 start:

It is a good idea for static and instance methods to have the same name, which is quite rare (IMO), but it is completely effective

Interestingly, this can cause overload resolution problems because methods are included even if there is no instance to call them For example:

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

    public static void foo(Object x) {
    }

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

The specification could have been designed like this (and called static methods), but it was an error:

Test.java:9: error: non-static method foo(String) cannot be referenced
                    from a static context
        foo("");
        ^
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>