繁体   English   中英

Java接口使用另一种接口类型的方法

[英]Java interface's method that uses another interface type

我的接口(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);

    }
}

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

实现接口B的类C不会覆盖接口B的方法。 我想您在这里想做的就是扩展接口B 但是类不能扩展接口。 您在这里可以做的是使C成为接口B扩展接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM