The Artima Developer Community
Sponsored Link

Java Answers Forum
static modifer in public static void main(Strin s[])

1 reply on 1 page. Most recent reply: Dec 3, 2004 5:38 AM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
guest

Posts: 9
Nickname: guest
Registered: Dec, 2003

static modifer in public static void main(Strin s[]) Posted: Dec 3, 2004 5:17 AM
Reply to this message Reply
Advertisement
what is use of static modifier in the public static void main(String a[])
method in java


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: static modifer in public static void main(Strin s[]) Posted: Dec 3, 2004 5:38 AM
Reply to this message Reply
First the basics (I don't know how much you know about the matter):

If you want to access a non static method in a class, you must first create an instance of that class:
A static method can be called without creating an instance.

class MyClass {
  public MyClass() {
  }
  public nonStaticMethod () {
  }
  public static staticMethod () {
  }
}
class MyOtherClass {
  public doSomething () {
    //this won't work
      MyClass.nonStaticMethod(); //in fact, it will produce a compile error
    //these lines will work
      MyClass.staticMethod();
      MyClass c = new MyClass();
      c.nonStaticMethod()
    //this will work too
      (new MyClass()).nonStaticMethod();
  }
}


Now the answer to your question:
If you call ">java -cp . MyStartClass", the engine won't create an instance of MyStartClass.

Therefore it can't access a non static method and that's why the main method has to be static.

Flat View: This topic has 1 reply on 1 page
Topic: Need file of words Previous Topic   Next Topic Topic: Copying folders and files

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use