Is it possible in Java to have a class inherit fro

2019-07-29 21:29发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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.



标签: java android oop