Thursday, March 30, 2017

Static Modifier in java

Static modifier:-

Static is the modifier applicable for methods and variables but not for classes.
We can’t declare top level class with static modifier but we can declare inner class as static (such type of inner class are called static nested classes)
In the case of instance variables for every object a separate copy will be created but in the case of static variables a single copy will be created at class level and stared by even object of those classes.


package com.javahighq;

public class Vesicle {

      static int x=34;
      int y=20;
      public static void main(String[] args) {
            Vesicle t=new Vesicle();
            t.y=41;
            t.x=40;
            Vesicle t2=new Vesicle() ;
            System.out.println(t2.y+"-----------"+t2.x);//20-----------40
      }
}


We can’t access instance members diereclty form sataic area but we can access from instance area directly. We can access static members from both instance and static area’s directly.


Ex:-

 consider the following declarations
1 int x=30;
2 static int x=10;
3 public void im(){
Syso(x);
}
4 public static void im(){
Syso(x);
}
1 & 3  true
1 & 4 false
2 & 3 true
2 & 4 true

Case 1:-

 overloading concept applicable for static methods including main method but JVM can always call String [] argument main method only.

Ex :-

package com.javahighq;

public class Vesicle {
public static void main(String[] args) {
      System.out.println("string[]");//string[]
}
public static void main(int[] args) {
      System.out.println("int[]");
}
}

 Other overloaded method we have to call just like a normal method call

Case 2:-

Inheritance concept applicable for static methods including main method. Hence while executing child class if child doesn’t contain main method then will be executed

Ex :-

package com.javahighq;

public class Vesicle {
public static void main(String[] args) {
      System.out.println("string[]");//string[]
}
}
class Bus extends Vesicle{
     
}

Case 3:-

Ex :-

package com.javahighq;

public class Vesicle {
public static void main(String[] args) {
      System.out.println("parent method");
}
}
//it is method hiding but not overrideing
class Bus extends Vesicle{
      public static void main(String[] args) {
            System.out.println("child method");
      }
}

It seems overriding concepts applicable for static methods but it is not overriding & if it is method hiding.

Note:-


For static methods overriding & inheritance concepts ate applicable but overriding concepts is not applicable. But instead of overriding method hiding concepts is applicable.

No comments:

Post a Comment