Any way to extend two or more classes in java?

前端 未结 12 1452
再見小時候
再見小時候 2021-01-17 02:20

I know that Java does not allow us to extend more than one class. I know that interfaces also exist and I don\'t want to use them this time. Is there some kind of trick or w

12条回答
  •  孤城傲影
    2021-01-17 02:55

    I am going to upset an awful lot of people by saying yes you can - kind of.

    It is certainly not easy and you have to use reflection but here you will find an example that allows you to dynamically extend one object with another. Obviously, once you can do that you can then extend another one too.

    Essentially, it uses the Proxy class to intercept method calls and direct them to one or other of two objects - this implements A overrides B. This is not quite what you are looking for but it could easily be tweaked to detect methods that exist in both classes and call them both - thus achieving A extends B dynamically - kind of.

    Note that you need to read the section entitled Dynamic Object Adapter using Dynamic Proxies section of the link.

提交回复
热议问题