简体   繁体   English

“继承”相同代码而不在Java中继承

[英]“inherit” same code without inheritance in java

I have a situation in my code where I have 2 classes inheriting from different classes, but still need to have more or less the exact same code. 我的代码中有一种情况,我有两个从不同类继承的类,但仍然需要或多或少具有完全相同的代码。 I am looking for a way to make their codes the same without having to copy/paste it each time I modify it. 我正在寻找一种使它们的代码相同的方法,而不必每次修改时都将其复制/粘贴。

For more information, I work on Android and I have two activity classes inheriting from either android.app.Activity or android.support.v4.app.FragmentActivity. 有关更多信息,我在Android上工作,并且有两个从android.app.Activity或android.support.v4.app.FragmentActivity继承的活动类。 Those class are exactly the same, but the distinction is needed further down in the code when dealing with fragments. 这些类完全相同,但是在处理片段时,需要在代码中进一步区分。 As a result I need exactly the same code on 2 different classes since java does not support multiple inheritance. 结果,由于Java不支持多重继承,因此我需要在2个不同的类上使用完全相同的代码。 Is there a way to do that in a less cumbersome ? 有没有一种方法可以减少麻烦呢?

You could use interfaces to extract the commonality of the two classes. 您可以使用接口提取两个类的共性。

Or you could use delegation instead of inheritance, putting the required functionality in some other class that your other classes call into. 或者,您可以使用委托而不是继承,将所需的功能放在其他类调用的其他某个类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM