Start New Discussion within our Software Development Community

Hi all

Can someone tell me the difference between

public static void main

and

private static void main?

What is public and what is private and static?

Thanks guys+girls

Static modifier is used to create variables and methods that will exist independently of any instance created for the class. Static members exists before any instance of the class is created.
Also there will be only one copy of the static member.

To call a static method displayRuns() of the class named Cricket we write

Cricket.displayRuns();

Class name is used to invoke the static method as static member does not depend on any instance of the class.

private static method means you can not invoke the method from outside the class as the method is private to the class.

Like the most common example, you want to know how many of the instance of the Dog class is created. To find out this we write the code as follows.

public class Dog
{
       private static int count;     //static member
 
       public Dog()
       {       count++;
       }
      
       public static void main(String a[])
       {   Dog d=new Dog();
           Dog dd=new Dog();
           new Dog();
           Dog.display();     
        }
private static void display()
{
      System.out.println(count);
}
}

Here in the example the private member is the count variable which is the static member. A private static method is loaded in the memory even before the instance of the class is created.
And since the member is private it can not be called from outside the class.

Hope it will help you

This article has been dead for over six months. Start a new discussion instead.