有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以为不同接口中的不同方法使用相同的名称吗?

我只是为了一些研究目的而学习Java。 我对Java中的接口机制有一个问题。 我不知道将接口理解为某种特殊的抽象类是否正确;但我不知道编译时使用的是哪种方法“pr(int_I)”:

public interface A {
    int flagA=0;
    void pr(int _i);
}

另一个界面B如下:

public interface B extends A{
    int flagB=0;
    double pr(int _i);
}

然后我使用接口a和B实现了一个类:

public class inter1 implements A,B {
    void pr(int _i){...};
    double pr(int _i){...};
}

它无法正确编译。当我使用接口B时,这里不会对接口A形成覆盖。但是返回类型是否足以区分两种方法

我已经查阅了Bruce Eckel在Java中的思想,但没有发现任何有用的东西

谢谢你抽出时间


共 (4) 个答案

  1. # 1 楼答案

    你对接口B的定义也会有编译错误

    因为方法pr()[在接口B中]在接口A中实现了pr(),但根据实现方法规则,返回类型将不兼容

    在实现方法中,返回类型应该是相同的类型,或者是instanceOf操作返回真值的任何类型。(协变类型)

    此外,只有在以下条件下才能区分这两种方法

    • 参数数量
    • 参数类型
    • 这些参数的顺序

    希望这有帮助

    祝你好运

  2. # 2 楼答案

    仅仅使用不同的返回类型是不够的

    这是因为编译器不知道调用哪个方法。如果任何返回值都被丢弃,这一点尤其正确

  3. # 3 楼答案

    在同一个类中,不能编写两个只改变返回类型的相同方法

    方法重载具有不包含返回类型的独特规则(重载方法可以具有不同数量的参数,类型的参数和顺序

    而且您的接口也不会被编译,因为它不是以正确的方式重写方法。 共变异类型仅适用于方法重载而不适用于方法重载

  4. # 4 楼答案

    Java语言规范section on Requirements in Overriding and Hiding解释了重写方法时返回类型应该如何关联:

    If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs.

    Section 8.4.5解释返回类型如何可以替换:

    A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2 iff any of the following is true:

    • If R1 is void then R2 is void.

    • If R1 is a primitive type then R2 is identical to R1.

    • If R1 is a reference type then one of the following is true:

      • R1, adapted to the type parameters of d2 (§8.4.4), is a subtype of R2.

      • R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9).

      • d1 does not have the same signature as d2 (§8.4.2), and R1 = |R2|.

    因此,如果方法pr的返回类型是void,那么接口B中被重写的方法也必须返回void。如果返回类型为int,则重写的方法还必须返回int。对于引用类型,返回类型应为子类型或可转换为子类型:

    interface A {
       int flagA = 0;
    
       Number pr(int _i);
    }
    
    interface B extends A {
       int flagB = 0;
    
       Integer pr(int _i);  // compiles fine
    }
    

    另一方面

    interface A {
       int flagA = 0;
    
       Integer pr(int _i);
    }
    
    interface B extends A {
       int flagB = 0;
    
       Number pr(int _i);  // does not compile
    }