sir-haver
sir-haver

Reputation: 3602

Android: Where is the constructor of AppCompatAcitivity?

I'm a beginner in Kotlin (and Android for the matter) and I saw that the first opening line of the MainAcitivty class is:

class MainActivity : AppCompatActivity() {

The braces after AppCompatAcitivty mean that this class has a constructor right? I searched inside this class and didn't find any constructor, so where is the constructor of AppCompatActivity?

Is it hidden in a super class that AppCompatActivity itself extends from? If so how can I track it?

Thanks in advance

Upvotes: 0

Views: 480

Answers (2)

Tenfour04
Tenfour04

Reputation: 93789

If no constructor is defined in Java, the class defaults to having an implicit constructor with no arguments and an empty initializer. It's the same in Kotlin...your class definition here for MainActivity has no constructor defined, so it implicitly has a constructor with zero arguments (although you can still define an initializer, but don't do this for an Activity--see below). If you subclassed MainActivity (provided it was marked open, you would have to call the implicit constructor like this:

class MyOtherActivity: MainActivity()

Also in Java, the default implicit constructor automatically passes back to the super constructor. If you follow the inheritence of AppCompatActivity all the way back up to Activity, you'll see that none of the classes have a defined constructor, so they are all empty.

Activities in Android must always have a single no-argument constructor because the OS instantiates them by reflection. You will never instantiate an Activity directly. Do your set-up in the lifecycle callbacks.

Upvotes: 1

GeRip003
GeRip003

Reputation: 11

It means the MainActivity extends the AppCompatActivity class. This is a classic inheritance. See example here.: https://kotlinlang.org/docs/tutorials/kotlin-for-py/inheritance.html But of course, it has a constructor, a default one.

Upvotes: 0

Related Questions