| Author |
How to call static methods from non static methods
|
Meir Yan
Ranch Hand
Joined: Apr 27, 2006
Posts: 597
|
|
Hello all i have class that holds static methods , this is utility class and i need one of the actions but i need it from non static method . is there any way to over come this ? call static method from non static method?
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14670
|
|
all static method from non static method?
Just call it the usual way : MyClass.myStaticMethod();
|
[My Blog]
All roads lead to JavaRanch
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3327
|
|
Non-static method of which class? Even if its in the same class and though its not advisable, you are allowed to call the static method from a non-static method wherein the reverse case is not true.
|
Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
|
 |
David McCombs
Ranch Hand
Joined: Oct 17, 2006
Posts: 212
|
|
It doesn't matter what type of method that is calling the static method is. The calling mechanism is the same. I can't think of a case where the method that gets called should ever care or need to know where the call is coming from. If you are calling the static method from outsize the class that the static method belongs to, it is NAMEOFCLASS.NAMEOFSTATICMETHOD(); If the call comes from an object from the same class as the static method: NAMEOFSTATICMETHOD() works just fine. However, you can use the class name in the call if you want, like in the second paragraph.
|
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
|
 |
arulk pillai
Author
Ranch Hand
Joined: May 31, 2007
Posts: 3188
|
|
If I have understood your question correctly You can call a static method from a nonstatic method as follows: But to call a non-static method from a static method you need to create an instance of that class:
|
Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3327
|
|
Or you can even call it in the traditional way, ClassName.methodName(), which does not cause any harm
|
 |
Meir Yan
Ranch Hand
Joined: Apr 27, 2006
Posts: 597
|
|
is there any problem to do that : new Class.NonStaticMethod()? i mean from the preformance point of view?
|
 |
Andris Jekabsons
Ranch Hand
Joined: Jan 20, 2004
Posts: 82
|
|
Did you mean " new MyClass().NonStaticMethod() "? This creates a new instance of MyClass, so if your constructor does some time consuming stuff, it will unnecessary decrease performance. At any rate, this is not a good coding style.
|
 |
 |
|
|
subject: How to call static methods from non static methods
|
|
|