Java- static modifier / Chapter -6/ Access Modifier


  1. "static" is a modifier applicable for methods & variables but not for classes.(not for top-level classes but for inner classes we can apply)
  2. We can't declare top level classes with static modifier but we can declare inner classes as "static".
  3. in the case of instance variables for every object a separate copy will be created but in the case of static a single copy will be created at the class level and this will be shared by every object of that class.  example:-
    class Test
    {
          static int x=10;
          int y=20;
          public static void main(String [ ]args)
          {
               Test    t1 =new   Test( );
                t1.x =  888;
                t1.y =  999;
               Test   t2 =new Test( );
               System.out.println(t2.x +".........."+t2.y);
          }
    }

    output is;
    888.........20


  4. We can't access instance member directly from the static area but we can access from instance area directly.Whereas we can access the static member from both instance & static area directly. 


Case Study:-
case 1:-
Overloading concept applicable for the static method including main( ) method But JVM will always call String[ ] argument main( ) method only.

example:-
class Test
{
      public static void main(String [ ]args)
      {
           System.out.println("String  [ ]");
      }
       public static void main(int  [ ]args)
      {
           System.out.println("int  [ ]");
      }
}
Output is:  String [ ]


case 2:-
Inheritance concept applicable for static method including main( ) method.
Hence while executing child class, if child class doesn't contain main( ) method then parent class main( ) method will be called.
example:-
class Parent
{
      public static void main(String [ ]args)
      {
           System.out.println("Parent main method");
      }
       
}
class Child extends Parent
{

}



















case 3:-
Overriding concept applicable for the static method but it is not overriding, it is method hiding.
example:-
class Parent
{
      public static void main(String [ ]args)
      {
           System.out.println("Parent main method");
      }
       
}
class Child extends Parent
{
        public static void main(String [ ]args)
      {
           System.out.println("Child main method");
      }
}



















No comments:

Post a Comment

Be the first to comment!

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.

Regards,
JavaByChetan
Back To Home

Flipkart End Of Season Sale






© Copyright 2017 Javabychetan.blogspot.com