This question was asked to me in an interview. Tired of googling here I am.
I have an interface with 100 methods. I don't want to implement all those 100 methods in a single class. Is there any way I could implement these 100 methods by using more than one class and not repeating the implementation ?
For Example : Class A implements first 10 methods(only). Class B implements next 10 methods(only) and so on.
Note : 1. All the classes which implements the interface must be concrete.
As far as my knowledge on java this isn't possible. He mentioned about adapter when he asked me this question. That made me think that there's a way to do it.
Can anybody clarify me on this ?
A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.
A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.
A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces.
Write an adapter with empty implementation of the 100 methods
class Adapter{
//write your empty implementations here as similar to KeyListener in Java
// They have written a keyAdapter and make use of key adapter.
}
ie) class Adapter implements interface1{
public void method1(){}
public void method2(){}
.....
}
You can extend the adapter class in some other class and just override the methods.
class A extedns Adapter{
public void method1(){
}
}
ie)
The concept you describe is called partial classes and Java does not have such a concept.
Here is a similar answer: A way to implement partial classes in java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With