gpt4 book ai didi

Java 方法签名和接口(interface)

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:54 26 4
gpt4 key购买 nike

我们知道,方法签名只包括方法名和参数列表,不包括方法返回类型。那么为什么我会收到以下代码的编译器错误,因为 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
}

重点是如果你在一个类(class)中尝试这个:

public void hello() {}
public int hello() {return 1;}

你会得到 Duplicate method hello() in type YourClass 错误,因为 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 方法签名和接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31987440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com