if a static method in a java program can only call other methods declared static and only access data declared static then how is main able to access all non static data and call all non static methods? does main have any special privileges?
2 replies to this topic
#1
Posted 15 May 2011 - 06:04 AM
|
|
|
#2
Posted 15 May 2011 - 07:56 AM
No, main has no special privileges, and it can't call non-static members or data. Observe:
public void nonStaticMethod()
{
System.out.println("Non Static Method called!");
}
public static void main(String[] args)
{
nonStaticMethod(); // results in compile error.
}
However, just like all static methods, main can create new objects that you can then call the non-static methods on.public class Test
{
public void nonStaticMethod()
{
System.out.println("Non Static Method called!");
}
public static void main(String[] args)
{
Test t = new Test();
t.nonStaticMethod(); // No problems
}
}
Wow I changed my sig!
#3
Posted 15 May 2011 - 01:28 PM
{Posted out-of-context almost-spammy link}
Edited by ZekeDragon, 15 May 2011 - 02:52 PM.
You got a warning
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









