"Static methods can access only static data and can call only other static methods."But main() is also declared as static wherein we are calling any method and accessing all sorts of data.pls explain.thanks in advance.

Showing Answers 1 - 11 of 11 Answers

Reddy

  • Sep 19th, 2006
 

Like Main method every static method can call the methods through instance, there is no difference between main() method and other static methods except main() method is invoked/called by JVM, but other methods we will call.

  Was this answer useful?  Yes

Main method is declaerd as static that means that jvm does not require any instance for calling that class

Static method or data does not belong to any object of the class but are class members that is global to all class .Any way these members can be behaved similar to object variable . Any object member being part of the object has to be called using any object name followed by member

  Was this answer useful?  Yes

Its true that static methods can access only static data and can call other static methods, but it applies only to those methods and data having the scope outside the accesing static method. Still the static method can have its own local non-static variables which may be used freely inside it and that's what you are concerned about.

Please note that even main() can access only the static data and static methods. Whatever non-static data is being used in main() must be the local variables defined and declared inside main() only. For e.g consider the String args[] parameter being passed to main, isn't that non static. Try defining some non-static variable outside main() and try accessing it, then try making that variable as static and then again try accessing it. Hope the doubt has been cleared out. :)

  Was this answer useful?  Yes

sachin

  • Sep 18th, 2007
 

If base class has a method name m2 which is not static then
public class derive extends base{
static int i =10;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("m1 derived"+i);derive dv = new derive();
dv.m2();
}
}
this code run how it is possible if main is static and method is non static

  Was this answer useful?  Yes

Amit Patil

  • Sep 19th, 2007
 

It is not possible to access non-static methods or variables even in main method. You have to create instance and access non-static methods in main

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions