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!
2
Answers
Yes
AppCompatActivity
is a subclass ofActivity
It doesn’t matter how many classes come in between a superclass and a subclass… there is still an "is a" relationship between them.
can you please specify what field is in the
activity
class and not in theAppCompatActivity
class?AppCompatActivity
is a direct subclass ofFragmentActivity
, i.e.FragmentActivity
is its direct superclass, the one itextends
. ButActivity
is still a superclass ofAppCompatActivity
, because it appears higher in the inheritance hierarchy, like in the image you posted: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 anObject
.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 usingoverride
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 thatFragmentActivity
has, which includes the stuff thatFragmentActivity
inherits fromComponentActivity
, and so on.Object
defines thetoString()
method, which is why every single class has that method – they all ultimately inherit fromObject
, but often not directly.