This Keyword

This

'this' is a keyword in java language which is used used in two different ways
  • this.
  • this( )
  • this.

    this. is used to differenticiate the local variables and global variable whenever both are same name

    this. always represents global variables

        class Demo
        {
        int x; // global variable
        void show() 
        {
        int x;  // local variable
        x=x; // this.x=x or x=this.x;  here this. is global variable
        System.out.println(x);
        }
        }
        class mm
        {
        public static void main(String args[])
        {
        Demo d=new Demo();
        d.show();
        }
        }
        
    

    this( )

    ' this( ) ' it is used call the multiple constructors whith the help of single object creation.
      // without this( ) program
      class Demo
      {
      Demo( )
      {
      System.out.println("This is NOPC")
      }
      Demo(int x)
      {
      System.out.println("This is 1PC")
      }
      Demo(int x,int y)
      {
      System.out.println("This is 2PC")
      }
      }
    class mm
    {
        public static void main(String args[])
     {
        Demo d1=new Demo();
        Demo d2=new Demo(10);
        Demo d3=new Demo(10,20);
      
     }
    }
    
     

    In this program object created multiple times so memory is allocated multiple times. To overcome this problems this( ) is introduced

      // with this( ) program
      class Demo
      {
      Demo( )
      {
      this(10);
      System.out.println("This is NOPC")
      }
      Demo(int x)
      {
      this(10,20);
      System.out.println("This is 1PC")
      }
      Demo(int x,int y)
      {
      System.out.println("This is 2PC")
      }
      }
    class mm
    {
        public static void main(String args[])
     {
        Demo d1=new Demo();
     }
    }
     
    For more Programs Click Here