Well. I am new to Java. I know that main needs to be static method. But I have read that an static method can call only other static methods ? Then how come we can call non-static methods ? Its a confusion rather than a question. For example
public class Function
{
public static int side = 10,area,vol;
public static void main(String args[])
{
System.out.println("programme to find area and volume");
Function fu = new Function();
fu.calarea();
}
public void calarea()
{
area = side*side;
System.out.println("finished calculating area now calling volume");
calvol();
}
public void calvol()
{
vol = area*side;
System.out.println("finished calculating volume now calling display");
display();
}
public void display()
{
System.out.println("side of a square ==>"+side);
System.out.println("area of a square ==>"+area);
System.out.println("volume of a square ==>"+vol);
}
}
In here, main() is a static method. So, it must call static methods only ? How come, it can call calarea() ? If I am right by creating a object ??
EDIT:
I had thought the same. And I know how to call static methods. I only want to know that if it is possible to call non-static methods(by any means), then why it is said that an static method can call only other static methods ?
That is either a misstatement or a misreading.
A more correct statement of the “rule” is that a static method cannot call instance methods without a specific (non-null) instance reference. Or to put it another way,
thisis not valid in a static method, so it cannot be used explicitly or implicitly to make method calls.Your example doesn’t break the rule … in either form. It is using an non-null object reference, and it is not using
thisexplicitly or implicitly.Most of the other subquestions are “mooted” by the above but …
Yes. It is necessary to create the object in order to have an object reference that you can use to call the instance method. There is no other way to call an instance method.