Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing one interface using multiple classes

Tags:

java

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 ?

like image 995
KarthickN Avatar asked Aug 03 '15 12:08

KarthickN


People also ask

Can multiple classes implement the same interface?

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.

How can interface be used in multiple classes?

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.

Can an interface be implemented by multiple classes C#?

A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Can an interface extend multiple classes?

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.


2 Answers

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)

like image 149
Shriram Avatar answered Sep 29 '22 13:09

Shriram


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

like image 45
Johannes Avatar answered Sep 29 '22 13:09

Johannes