加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:26:42 所属栏目: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
这两个功能是否过载

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("");
        ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读