-2

I know main() method is a static method, I have seen the Object class methods but main() method is not defined there, then how we are using main() method in our java classes without importing related class?

Charan
  • 1
  • 3
  • I don't know what you think `static` means, but you are defining `main()` yourself, in your class – Tim Apr 13 '18 at 11:02
  • It is defined in the JLS, it is technically a convention used by Java that is not enforced by technical means (if you call it something else, or if the signature doesn't match the requirements of the JLS, then it is simply a normal method, and can't serve as the entrypoint of an application). – Mark Rotteveel Apr 13 '18 at 11:05
  • See [JLS §12.1.4](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.1.4). – lexicore Apr 13 '18 at 11:10

2 Answers2

2

I think I can see where your confusion comes from.

We often use interfaces to define certain contracts. Like the Runnable interface which defines the run() method which will be called by executors. Alternatively this could be a class with an abstract method, conceptually it's the same.

You also need such a contract for the entry point of your Java application. It was quite natural that you were looking for it somewhere in base Java classes like Object.

However, the main() method is different. Its "contract" is defined not by an interface but by specification, i.e. Java Language Specification. The whole §12 is dedicated to execution and §12.1.4 specifies the "contract" for the main() method.

On a side note, it is not so rare that certain "contracts" are not defined by interfaces or abstract methods but via formal specification. Another example of this are readObject() and writeObject() methods.

lexicore
  • 42,748
  • 17
  • 132
  • 221
  • thank u, can you name some other contracts like main() method if any? – Charan Apr 13 '18 at 11:24
  • @Charan You better ask this as a separate question. Something like Which non-interface contracts exist in Java? I could name `Cloneable` which is well, an interface but broken. Or `before`/`afterUnmarshal` callbacks in JAXB. All these `read...`/`write...` methods in serialization. `serialVersionUID`. There are many things, I won't be able to recall everything. – lexicore Apr 13 '18 at 11:29
0

You're just creating a new method the same way you'd create another one

The only particular thing about main is that its signature

public static void main(String[] args)

can be the entry point of any Java application

Alberto S.
  • 7,409
  • 6
  • 27
  • 46