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

method question

 
Mitch Krah
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:
static void printResults(int m, int x, int s, double a) {
 
Paul Santa Maria
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic