Michael Michael - 4 months ago 23
Java Question

Do all Android classes extend Activity?

I'm going through some Android development tutorials, and I notice that some classes extend Activity, and others extend ListActivity for example.

By default, does a newly created class implicitly extend Activity or do you need to explicitly extend it?

Also, when a class extends ListActivity, why do you not have to extend Activity? Or does ListActivity already extend Activity?

I read a few similar questions but it wasn't quite clear.

Answer

By "default", all Android Activities extend Activity.

By default, does a newly created class implicitly extend Activity or do you need to explicitly extend it?

You have to explicitly state that it should extend Activity if it does not already and if you plan to use it as an Activity. Kindly note that you there are times you wouldn't do it. For example, when you have a class for your objects or whatnot, then you don't need to extend Activity any longer.

Also, when a class extends ListActivity, why do you not have to extend Activity? Or does ListActivity already extend Activity?

ListActivity, AppCompatActivity, and any other class that ends in -Activity are "children of the Activity class. So by extension, extending by these "children" would already extend from the parent Activity class and you'll no longer need to do something like YourActivity extends ListActivity, Activity. I think Android Studio will give you an error if you do.

The difference between an Activity and a ListAcivity is that a ListActivity will require you to override several methods because it is expecting a ListView in its content.

Comments