简体   繁体   中英

Implementing interface in java

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

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.

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

}

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