public class Function
{
public static void main(String args[])
{
System.out.println(power(3,2));
System.out.println(power(3,2));
System.out.println(power(2));
}
public long power(int m)
{
return m*m;
}
public long power(int m,int n)
{
long product=1;
for(int i=1;i<=n;i++)
{
product=product*m;
}
return product;
}
}
Compiler displays this error :-
Function.java:5: non-static method power(int,int) cannot be referenced from a static context
[edit]
Sorry about the indentation thingy :/ I'll keep that in mind from now on.
Ok so I just added static keyword and it's working fine now. What difference does this static keyword make ? I am a beginner to java and have not yet studied about what static does. I sure will read it in further chapters of the book but someone please give me an idea what it does. Thanks.
A shortcut rule of thumb (without full background explanation) is that static methods/functions can't call non static methods/functions so anything you want to call from your main function will need to have the static keyword in front of it.
The core issue is that Java is an object oriented language and static vs. non-static requires quite a bit of pre-requisite knowledge of object orientation. One of the disadvantages of Java is that it does require beginners to jump through a few hoops of this type as they are learning, this all stems from the object-oriented nature of Java and once you understand OO it will all fall into place (the decisions made by the language designers aren't necessarily the best ones but they are logical)
I hope you won't find it patronising if I don't go into an explanation of what static is. I can tell you that it's not a particularly difficult concept but it just relies on a few building blocks of OO concepts and a premature attempt at explanation (by me anyway) might put you off.