-6

Why do we always write this:

public static void main(String args[])

As the Object class is a parent class of all the classes in Java, so can we write

public static void main(Object args[])

instead of

public static void main(String args[])

?

peterh
  • 11,875
  • 18
  • 85
  • 108
  • 2
    How would you pass an `Object` to the command line? – Federico klez Culloca Jul 24 '23 at 14:12
  • You know what the `String args[]` part of that method is for, right? It's for passing [command line arguments](https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html) when starting the program. Now I can easily type a String command line argument, but I'm not sure how I could "type" a random Object into my console. – OH GOD SPIDERS Jul 24 '23 at 14:12
  • 4
    What happens when you try? – David Jul 24 '23 at 14:15
  • Note c-style array declarations are typically discouraged in Java (so `String[] args` instead of `String args[]`). This style makes readily apparent one thing: That `String[].class != Object[].class` (they're fundamentally different types!). Java arguments are type invariant: you cannot pass a different type (parent or child) than expected for any method. Note generic bounds are still the same type. Return values are covariant: You can return a more specific (i.e. subclass) type, but never a more general one. – Rogue Jul 24 '23 at 15:08

1 Answers1

0

public static void main(String[] args) is the interface of a Java binary to the external world. More clearly, to an external command line environment. It should not be always so: for example, in an ancient world, as there were Java "applets" (essentially, GUI Java Apps running as today a Javascript runs in a div/iframe), then they used a different initiator method. Or, in any case, if the environment is not a command line environment, like if you develop an app to an app server, then the initiator method will be likely different.

However, in the command line world, you give string arguments to the processes you start. You can not parametrize, for example, a shell script with an Object, you only can do with strings.

peterh
  • 11,875
  • 18
  • 85
  • 108