使用多个类实现一个接口 [英] Implementing one interface using multiple classes

查看:555
本文介绍了使用多个类实现一个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在接受采访时被问到了我。我在这里厌倦了谷歌搜索。

This question was asked to me in an interview. Tired of googling here I am.

我有100个方法的接口。我不想在一个类中实现所有这100个方法。有没有办法通过使用多个类而不重复实现来实现这100个方法?

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 ?

例如:
A类实现前10个方法(仅限)。
B类实现接下来的10个方法(仅限)等等。

For Example : Class A implements first 10 methods(only). Class B implements next 10 methods(only) and so on.

注意:
1.所有实现接口的类必须具体。

据我所知,这是不可能的。当他问我这个问题时,他提到了适配器。这让我觉得有办法做到这一点。

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.

有人可以澄清一下吗?

推荐答案

写一个适配器100个方法的空实现

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)

这篇关于使用多个类实现一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆