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.
-
for all classes: make it a default method. "only few classes", you can't. what's in an interface goes for all the implementations– StultuskeApr 8, 2019 at 12:00
-
4Use an abstract class that implements the method, let your classes extend this abstract class.– user11044402Apr 8, 2019 at 12:01
-
If your classes use inheritance, you could update it in the base classes.– PatrickApr 8, 2019 at 12:02
-
Probably, you need an abstract class?– dehasiApr 8, 2019 at 12:30
-
Step 1. Refactor so you don't have 1,000 classes– John WuApr 8, 2019 at 16:29
2 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).
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.