| Author |
method question
|
Mitch Krah
Ranch Hand
Joined: Sep 06, 2004
Posts: 41
|
|
I have the following code: First he compiler made me put the printResults outside of main. I don't understand this??? Why can't I have a method inside of main? Next the compiler will not let me call printResults from inside of main. When I call the printResult method (as shown above), I get an error saying you cannot call a non-static method from a static context??? Pleasa help? Thank you, Mitch [ edited to preserve formatting using the [code] and [/code] UBB tags -ds ] [ December 05, 2004: Message edited by: Dirk Schreckmann ]
|
 |
Paul Santa Maria
Ranch Hand
Joined: Feb 24, 2004
Posts: 236
|
|
Hi - You've actually asked a very important - and, in some ways, very subtle -question. You can get a good, detailed explanation here: http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html Bruce Eckel ("Thinking in Java, 3rd Ed") explains it as follows: "[A static method is] the equivalent of a global function (from C)... It means that there is no 'this' (no per-instance data) for that particular method. "You cannot call non-static methods from inside static methods (although the reverse is possible", and you can call a static method for the class itself, without any object. In fact, that's primarily what a static method is for." Please take a look at the JavaDoc for "java.lang.Math". You'll notice that most of the math functions (abs(), sin(), cos(), etc etc) are all static functions. The reason is simple - you shouldn't have to create an entire object just to get the absolute value of a number. You just call ... a "static method": "abs (x)". 'Hope that helps .. Paul Santa Maria
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
Try this: static void printResults(int m, int x, int s, double a) {
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
Paul Santa Maria
Ranch Hand
Joined: Feb 24, 2004
Posts: 236
|
|
With all due respect, you shouldn't just "try static printResults()..." as you need to understand the (important) difference between static and non-static methods and data. For purposes of illustration, here's a slightly different example, using non-static methods: 'Hope that helps .. PSM
|
 |
 |
|
|
subject: method question
|
|
|