Is it possible in Java to have a class inherit fro

2019-07-29 21:44发布

I have a parent class in Android that inherits from Activity and all my other activities inherit from that parent class. This parent does some life cycle stuff in onPause and onResume that all my activities need. The problem is I have a Map activity that must inherit from Android's MapActivity yet I still need this activity to have my parent classes life cycle methods. Is there a way to have the MapActivity inherit from two parents? Or maybe a partial class I'm not really sure here. Any Ideas would be great.

Thanks,

Bryan

标签: java android oop
4条回答
beautiful°
2楼-- · 2019-07-29 22:07

The short answer is no. You cannot have a class that inherits from two classes in Java. The standard recommendation would be to use an interface, but I don't think that's right for you in this case.

Perhaps that you can achieve the code reuse you are looking for by using composition, for example, instead of inheritance. If you post a code example, I could give you a more specific answer.

查看更多
Juvenile、少年°
3楼-- · 2019-07-29 22:16

Sorry but in Java you can only extend one class. However you can implement multiply interfaces. You could have a BaseMapActivity class extend a MapActivity and then have your MainMapActivity extend that BaseMapActivity. The easiest way would be to copy the code from the already existing base Activity and put it into the MainMapActivity.

查看更多
Viruses.
4楼-- · 2019-07-29 22:19

In Java you can only extend from a single class, however you are able to implement multiple classes from a single class. Another thing to consider is chaining extended subclasses together (this simulates multiple inheritance).

A better description can be found here: http://www.javaworld.com/javaworld/jw-10-2005/jw-1024-multiple.html

查看更多
姐就是有狂的资本
5楼-- · 2019-07-29 22:31

It’s funny, I had exactly the same problem earlier this day (but with a PreferenceActivity).

Unfortunately, I don’t think it’s possible, I ended up making a copy of my parent class and changing the name and the extends Activity into extends PreferenceActivity.

查看更多
登录 后发表回答