-1

In Java, the first method to be run is public static void main(String[] args)

In android, the first method to be run is protected void onCreate(Bundle savedInstanceState)

I was always wondering why does the first method in Java have to be static but in android doesn't? Would anyone please help me to get this thing clear in my mind?

Johnny Cheuk
  • 237
  • 2
  • 15
  • Possible duplicate of [How can Android source code not have a main method and still run?](http://stackoverflow.com/questions/4221467/how-can-android-source-code-not-have-a-main-method-and-still-run) – WalterM Jan 10 '16 at 11:46
  • But I'm asking about why it has to be static – Johnny Cheuk Jan 10 '16 at 11:47
  • 3
    Probably because you can call static methods without instantiating anything. – WalterM Jan 10 '16 at 11:48
  • static is simpler. "If a method is declared as static then we can call that method outside the class without creating an object": http://stackoverflow.com/a/29547192/1206341 – greenmarker Jan 10 '16 at 11:52
  • But why in android doesn't need static? – Johnny Cheuk Jan 10 '16 at 11:53
  • @JohnnyCheuk you don't need to cause you only declare activities in manifest and you do not instantiate them. onCreate is called the first time activity is created. Its a lifecycle method. Your manifest file is parsed and the launcher activity launched. Its the job of android. http://developer.android.com/guide/topics/manifest/manifest-intro.html – Raghunandan Jan 10 '16 at 11:58

2 Answers2

1

These are two different scenarios. We have a general java language run by a java virtual machine. This jvm is designed to call a specific entry point for all applications. Thus this have to be as generic as possible.

Android runtime and many other like WARs, Applets, Servlets are "higher" apis. Thus they have all their specific entry points. Since these apis are already running within general jvm with an own main() method, they are able to implement more complex and domain specific entry points. Thus in this case the android runtime creates an object of a given class and invokes the methods designed by the api.

See also:

And many other resource.

Community
  • 1
  • 1
Marcinek
  • 2,144
  • 1
  • 19
  • 25
0

Because Android studio is based on a framework. If you take a look at the callstack when breaking on 'onCreate', you can see that a static main() method is called & creates an instance of your MainActivity class.

http://picpaste.com/stack-FOnB69o6.png

Niek Vandael
  • 394
  • 1
  • 3
  • 15