【问题标题】:Java interface's method that uses another interface type使用另一种接口类型的 Java 接口方法
【发布时间】:2018-04-07 21:54:52
【问题描述】:

我的接口 (A) 中有一个方法,它接受另一个接口 (B) 作为参数。当我去实现 (A) 并传递一个实现接口 (B) 的对象 (C) 时,我被困在向下转换 (B) 到所传递对象的正确实现 (C) 上。

例如...

public interface A {
    public void theMethod(B theObject);
}

public interface B {
    public Properties jarJar();

    public boolean isActuallyAJedi();

    public void srsly();
}

public class C implements B {
    //mumbo dumbo stuff from B
}

public class D implements A {
    public void theMethod(B theObject) { // <------ I would prefer to explicitly define C as it is implementing B
        C theUpcastedObject = (C) theObject; // <------ I want to avoid downcast here

        theUpcastedObject.isActuallyAJedi();

        theObject.srsly(); // <----- won't work because it is not aware of the implementation...
    }
}

public class Main {
    public static void main(String[] args) {
        D stuffIWillDo = new D();
        B theObject = new C(); // explicitly showing the implementation here...

        D.theMethod(theObject);

    }
}

我希望这能很好地解释这一点!

【问题讨论】:

  • 请注意,这是向下转换,而不是向上转换。但听起来你想要泛型。
  • 你无法避免向下转换,因为任何使用接口 A 使用你的 C 类的人都会认为 B 类的任何对象都可以传递给这个方法。如上所述,如果它们适合您的用例,您可以使用泛型。
  • 就像@OliverCharlesworth 说的,对我来说听起来像是泛型
  • 我认为你不需要强制转换,顺便说一下它是向下强制转换,在这种情况下,因为 C 必须实现 B 拥有的方法。所以,当你将 theObject 传递给 theMethod 时,并且没有声明新的引用即 theUpcastedObject,你可以直接使用它。
  • 这里不需要泛型。正如@snr 所解释的,您只使用在接口 B 中声明的方法。因此,您的方法没有理由必须知道确切的实现类型。您对theObject.srsly() 的评论不正确。此方法在接口 B 中声明,因此您可以调用它。

标签: java interface


【解决方案1】:

实现接口B的类C不会覆盖接口B的方法。我猜你在这里尝试做的是扩展接口B。但是一个类不能扩展一个接口。您可以在这里做的是使C 成为一个接口,该接口将扩展接口B

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多