Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 726
rohan Avatar asked Apr 08 '19 11:04

rohan


1 Answers

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

E.g:

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 (e.g: 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).

like image 142
Marko Pacak Avatar answered Nov 15 '22 14:11

Marko Pacak