rohan
rohan

Reputation: 151

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.

Upvotes: 7

Views: 376

Answers (2)

Syed Zubair Ahamed
Syed Zubair Ahamed

Reputation: 14

if you have to use previous versions of Java, you could simply used abstract classes,it is one such way to implement the above scenario.

Upvotes: 0

payloc91
payloc91

Reputation: 3809

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

Upvotes: 14

Related Questions