Static Members and “this” Keyword in java

Static Members and This Keyword in java

Static Members

It is possible to create members that can be used by itself, without reference to specific instance.It can be achieved by preceding its declaration with static keyword.

      In static member declaration,
  • Members can be accessed before any object of its class are created.
  • They can only call other static methods.
  • They must only access static data.
  • They cannot  refer to this or super in any way.
You can declare both method and variable to be static.Main()  is declared as static because it must be called before any objects exits.Instance variables , essentially, global variables are declared as static.When object of its class are declared, no copy of a static variable is made.All instance of the class share same static variable.

Example:

class pairosoft {
                static int a = 3;                               //static variable 
                static int b;
                static void meth(int x)                   //static method
                {
                                System.out.println(“X = " + x);
                                System.out.println(“A= " + a);
                                System.out.println(“B= " + b);
                }
                static                                             //static block
               {
                                System.out.println("Static block initialized.");
                                b = a * 4;
                }
                public static void main(String args[]){
                meth(42);                                   //static method call
                }
}

Output:-

Static block initialized
X = 42
A = 3
B = 12

This Keyword

Java defines the this keyword to allow this.this is always a reference  to the object on which the method was invoked.When a local variable has the same name as an instance variable, local variable hides the instance variable.this can be used to resolve any namespace collision that might occur between instance variables and local variables.

Example:

public class Pairosoft{ 
    int a;
    int b;
   
    void method(int a,int b){
        this.a=a;
        this.b=b;

        System.out.println("value of a is:"+a);
        System.out.println("value of b is:"+b);
    }
    public static void main(String[] args) {
        Pairosoft p1=new Pairosoft();
        p1.method(10,20);
    }
}

Output:- 

value of a is:10
value of b is:20







More will come idea if you watch this video:-







Post a Comment

0 Comments