Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static block

 
prashant panigrahi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between static block and method
 
Ben Ooms
Ranch Hand
Posts: 47
Debian Eclipse IDE Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static block is executed at class loading and a static method when its called.

See this example:


When the Bar main is executed class Foo is loaded at line 12 and produce:
static block called
when line 13 is executed static method of Foo is called and produce:
static method called


regards,
Ben
 
Rumesh Eranga
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also to access a non static method you have to create an object first but not for a static method.
 
prashant panigrahi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Ben and Rumesh
 
Subhash Pavuskar
Ranch Hand
Posts: 57
Chrome Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to this point ,In java we have two types of methods,
1. instance methods
2static methods.
Static methods can't use any instance variables. The this keyword can't be used in a static methods. You can find it difficult to understand when to use a static method and when not to use. If you have a better understanding of the instance methods and static methods then you can know where to use instance method and static method.




Ben Ooms wrote:A static block is executed at class loading and a static method when its called.

See this example:


When the Bar main is executed class Foo is loaded at line 12 and produce:
static block called
when line 13 is executed static method of Foo is called and produce:
static method called


regards,
Ben
 
Campbell Ritchie
Sheriff
Pie
Posts: 50225
79
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Subhash Pavuskar wrote:. . . The this keyword can't be used in a static methods. . . .
Nor can the keyword super.

Nice post there
You can find it difficult to understand when to use a static method and when not to use.
Try searching for “Campbell Ritchie classification of methods” and you find this. Click the link and it will give hints about when methods might well be static.
A static method does not require use read or investigate any information about an object (of the same class). A static method does not record write alter or manipulate any information about an object (of the same class).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic