简体   繁体   中英

“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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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