Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

static method

Status
Not open for further replies.

WebGoat

MIS
Jul 16, 2005
85
US
when do i use static method ?
op1.

Code:
Myclass a=new Myclass()
String x=a.mymethod();



String x=Myclass.mymethod(); // staic method

which one is good ?
 
its not clear yet.

suppose, i have to pass a parameter to a method and the method should return a value. so what would be a good design ?

declaraing a static method or declaraing a simple method ? which is one is better ? both of them will work . is not it ? but which one is better ? and why ?
 
If your method does not depend on the state of the class, aka: doesn't use member-variables, then it's a good idea to make this visible by declaring your method static.

Other Classes may use this method without creating an object of this class first, which will be confusing, if that object is never used again.

Perhaps this is a minor performance benefit (no ctor, no gc needed).

But if your design might be evolved, and later implementations might depend on an inner state of an object, it will be harder to refactor.
Perhaps from the logic of the program, there is allways an object of that class available.

seeking a job as java-programmer in Berlin:
 

If your method does not depend on the state of the class, aka: doesn't use member-variables, then it's a good idea to make this visible by declaring your method static.

Other Classes may use this method without creating an object of this class first, which will be confusing, if that object is never used again.


excellent. i was looking for this . thank you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top