| Author |
calling a static method from main?
|
Sam Cooper
Greenhorn
Joined: Feb 21, 2002
Posts: 14
|
|
I had come across this in a mock exam. public class Test{ public static void main(String[] args){ int[] a = {1}; Test t = new Test(); t.increment(a); System.out.println(a[a.length - 1]); } void increment(int[] i){ i[i.length - 1]++; } } My initial guess is that you can call a non static method from a static (main), so this should result in a compile tim error. But the answer that was given to be Complies and runs printing out 2. Could some on please let me know whats going on here SAM
|
 |
Sam Cooper
Greenhorn
Joined: Feb 21, 2002
Posts: 14
|
|
I MEAN My initial guess is that you CANNOT call a non static method from a static (main), so this should result in a compile time error. But the answer that was given to be Complies and runs printing out 2. Could some on please let me know whats going on here SAM
|
 |
Holmes Wong
Ranch Hand
Joined: Feb 18, 2002
Posts: 163
|
|
Originally posted by Sam Cooper: I had come across this in a mock exam. public class Test{ public static void main(String[] args){ int[] a = {1}; Test t = new Test(); t.increment(a); System.out.println(a[a.length - 1]); } void increment(int[] i){ i[i.length - 1]++; } } My initial guess is that you can call a non static method from a static (main), so this should result in a compile tim error. But the answer that was given to be Complies and runs printing out 2. Could some on please let me know whats going on here SAM
Here is the rule: you cannot call a non-static method from a static method, but you can use a reference to call a non-static method. Say, if you do: increment(a); //illegal Test t = new Test(); t.increment(a); //legal
|
 |
Sam Cooper
Greenhorn
Joined: Feb 21, 2002
Posts: 14
|
|
Holmes: Makes sense, Thanks
|
 |
 |
|
|
subject: calling a static method from main?
|
|
|