开发者

Runtime determination of base class at runtime in Java

开发者 https://www.devze.com 2023-03-20 19:53 出处:网络
I have two classes, one which is hardware-depen开发者_C百科dent and one which is not (let\'s call them HardwareDependent and HardwareIndependent respectively).The Hardware dependent class extends the

I have two classes, one which is hardware-depen开发者_C百科dent and one which is not (let's call them HardwareDependent and HardwareIndependent respectively). The Hardware dependent class extends the hardware independent class. Now I have another class which at least must be an extension of the HardwareIndependent, but I would prefer it to be an extension of HardwareDependent when possible so it may leverage the additional functionality. Is there a possibility of using reflection or something else to accomplish this? Or is this a total technical impossibility? I suppose if all else fails, I could write the class twice, but it seems to me that is an ineffective approach. Thanks for any help in advance.


Inheritance is fixed at compile time.

It sounds like you don't want your new class to extend HardwareIndependent or HardwareDependent; you want it to use an object which could be either. You want composition and not inheritance. You're third class (we'll call it HardwareComposite) has a reference to a HardwareIndependent. Then, you can check if it is HardwareDependent at runtime with the instanceof operator, and if so cast it to HardwareDependent and use the additional facilities that provides.

If your design is forcing you to mix concepts of inheritance and composition, you might look into the Facade and Factory patterns.

0

精彩评论

暂无评论...
验证码 换一张
取 消