java 函数签名_Java方法签名和接口

我们知道方法签名只包括方法名称和参数列表,但不包括方法返回类型.那么为什么我为以下代码收到编译器错误,因为java不区分具有相同签名的方法.

public class InterfaceTest implements I2{

public void hello(){ }

public void world(){ }

}

interface I1{

public int hello();

}

interface I2 extends I1{

public void world();

}

解决方法:

你这里没有overloading,你是overriding和hidding方法,但没有正确的方法….有2种可能解决你的问题:

public class InterfaceTest implements I2{

public void hello(int a){ } // overloaded method

@Override

public int hello(){ return 1; } // overriden method

public void world(){ } // this hides I1 method

}

如果你在一个类中尝试这个,那就是:

public void hello() {}

public int hello() {return 1;}

您将在类型YourClass错误中获得Duplicate方法hello(),因为要在overloading方法中您必须更改签名的FormalParameterListopt:

If two methods of a class […] have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

最后但不是最不重要的一点:

方法签名仅包括方法名称和参数列表,但不包括方法返回类型

根据JSL §8.4,当你声明一个方法时:

MethodDeclaration:

MethodHeader MethodBody

MethodHeader:

MethodModifiersopt TypeParametersopt Result MethodDeclarator Throwsopt

MethodDeclarator:

Identifier ( FormalParameterListopt )

所以当你这样做时:

public int hellow(int number) throws Exception;

//| | | | └ throwing an exception (Throwsopt)

//| | | └──────────── receiving one int argument (MethodDeclarator FormalParameterListopt )

//| | └─────────────────── name hellow (MethodDeclarator Identifier)

//| └─────────────────────── returning an int (Result)

//└────────────────────────────── is a public method (MethodModifiersopt)

标签:java,methods,interface

来源: https://codeday.me/bug/20190717/1489087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值