java – 彼此是静态和非静态重载

这两个功能是否过载

class yogi{

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

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

}

解决方法

是的,那些是超载.从 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.

对于静态和实例方法具有相同名称一个好主意是相当罕见的(IMO),但它完全有效.

有趣的是,这可能会导致重载解析出现问题,因为即使没有实例调用方法,也会包含方法.例如:

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

    public static void foo(Object x) {
    }

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

规范本来可以设计成这样就好了(并调用静态方法)但是它是一个错误

Test.java:9: error: non-static method foo(String) cannot be referenced
                    from a static context
        foo("");
        ^

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...