Search code examples
javaandroidandroid-studioandroid-activityextends

The class AppCompatActivity is a subclass of Activity?


Hi guys I've a more theorical question.

Is AppCompatActivity a subclass of Activity?

The AppCompatActivity class is a subclass of the FragmentActivity class directly and the ComponentActivity class indirectly, and these superclasses are subclasses of the Activity. This makes AppCompatActivity a subclass of the Activity? AppCompatActivity extends FragmentActivity

It is not a subclass directly, but still inherits some constants and fields from the Activity. Inherited constants and fields from Activity

This is why I am in doubt, can someone help me with that?

Thanks!


Solution

  • AppCompatActivity is a direct subclass of FragmentActivity, i.e. FragmentActivity is its direct superclass, the one it extends. But Activity is still a superclass of AppCompatActivity, because it appears higher in the inheritance hierarchy, like in the image you posted:

    A screenshot of the AppCompatActivity docs, showing the inheritance hierarchy

    Every class has one direct superclass (single inheritance) - if you don't specify one, the class inherits from Object. Everything ultimately inherits from that, which is why every class is an Object.

    When you create a class, you're taking its superclass as a starting point - it is that superclass, so you have all the same methods, the same fields, etc. All the stuff you declare in your class is effectively adding to that superclass - that's why the keyword is extends, right? So all the superclass stuff is included, you can't remove it (beyond using override to replace the behaviour - and you can still call the original method from the superclass if you want!).

    That's the point of inheritance - you take existing structure and functionality, and derive something more specific that makes use of it all. And this applies all the way up the chain - AppCompatActivity has everything that FragmentActivity has, which includes the stuff that FragmentActivity inherits from ComponentActivity, and so on. Object defines the toString() method, which is why every single class has that method - they all ultimately inherit from Object, but often not directly.