Jump to content

confused about main's static status

- - - - -

  • Please log in to reply
2 replies to this topic

#1
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
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
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
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
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
{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