Reputation: 28
I'm developing a java program and my problem is that I want to write a general method for calling a specific method on a few classes, and the class is not known.
for example in normal use i write this piece of code for RootLayoutController class and it works:
RootLayoutController controller = loader.getController();
controller.setMainApp(this)
but the problem is that i have to write a lot of methods to call them! so i created PageController interface ( with setMainApp() inside ) and implemented it in RootLayoutController and other classes ; then changed the method to this:
Object controller = loader.getController();
((PageController) controller).setMainApp(this);
but it throws classcastexception and I don't know much about interface so I can't debug it! thanks so much
Upvotes: 0
Views: 128
Reputation: 1651
Under java 8, file PageController.java (interface):
package test;
@FunctionalInterface
public interface PageController {
void setMainApp(PageController c);
}
File PageControllerImpl.java (test implementation):
package test;
public class PageControllerImpl implements PageController {
@Override
public void setMainApp(PageController c) {
// TODO your implemenrtation
}
public static void main(String[] args) {
PageController testController = new PageControllerImpl();
testController.setMainApp(testController);
}
}
Upvotes: 0
Reputation: 34146
If you have an interface PageController
, you can do (because a RootLayoutController
is a PageController
.):
PageController controller = loader.getController();
and then, there is no necessity to cast:
controller.setMainApp(this);
This is why interfaces exist.
Upvotes: 1