简体   繁体   中英

Java interface's method that uses another interface type

I have a method in my interface (A) that accepts another interface (B) as a parameter. When I go to implement (A) and pass an object (C) that implements interface (B), I am stuck downcasting (B) to the right implementation (C) of the passed object.

For example...

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);

    }
}

I hope this explains this well!

The class C which implements the interface B doesn't override the methods of interface B . I guess what you are trying to do here is extending the interface B . But a class can't extend an interface. What you can do here is make C an interface which will extend interface B .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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