简体   繁体   中英

how can we implement methods in multiples classes if we add methods in interface

In an interview interviewer asked this question. In an Interface1 there are 10 methods and implementing that Interface1 there are 1000 classes. Later in Interface1 I have added 11th method. How can you implement that 11th method in all classes. later he asked how can you implement in only few classes. Because of 1000 classes you cannot just go to each class and implement, its time taking. Can you tell me how to solve.

He was likely hinting at default methods in interfaces (available only from java 8 ).

Eg:

interface MyInterface {
    default void method() {
        // do stuff...
    }
}

All classes implementing the interface will inherit the method, you can yet override it in case you need specific behavior.

class MyClass implements MyInterface {

    @Override
    public void method() {
        // do stuff...
    }
}

Also, you can leave the base method blank (that does nothing) and then override it in your 11 classes. Or you can have another interface (eg: SubInterface ) extend MyInterface , override the base method and have your 11 classes implement directly the SubInterface so they inherit the most specific behavior. There are countless possibilities for what you have asked (including abstract classes, as someone mentioned in the comments).

如果你必须使用以前版本的Java,你可以简单地使用抽象类,它是实现上述场景的一种方式。

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