• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static method & class  RSS feed

 
Rahul Shilpakar
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please give me the reason

i wrote the code

class Example{

static A(){
// somthing
}

public static void main(String []args){
Example.A(); // line 1
}
}

this runs fine. tell me how can be a static method of the class Example is called by the name of class only. i.e. (Same in the case of Math class)
Why there is no need to create explicit object of Example class?
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class Example{

static A(){
// somthing
}

public static void main(String []args){
Example.A(); // line 1
}
}

this runs fine. tell me how can be a static method of the class Example is called by the name of class only. i.e. (Same in the case of Math class)
Why there is no need to create explicit object of Example class?



Error in code: there is no return type of static method A(). Fix it!

static methods are called class level methods. You think about main() method, do you ever need to create an instance of the class to call the main() method; NO!
You need not to create an instance of the class to call its static methods.
Although it you use the class reference variable to access it, it is provided;



Thanks and Regards,
cmbhatt
 
Rahul Shilpakar
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow, it was nice explaination. thank you very much.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!