Sunday 23 October 2016

this keyword

class
We can apply on 
  1. Variables
  2. methods
  3. constructors
1. this keyword on Variables 
  • this keyword we can apply on variable to refer current class instance variable.
-------------------------------------------------------------------
Program         :        this keyword
Program name  :        Student1.java
Output            : 
        Id is :1
        Name is :Sravan
        Id is :2
        Name is :Amar
class Student1
{
int id;
String name;
  Student1(int id,String name)
  {
  this.id = id;
  this.name = name;
  }
  void display()
  {
 System.out.println(“Id is :”+id);
 System.out.println(“Name is :”+name);
  }
  public static void main(String args[])
  {
 Students1 = new Student1(1,"Sravan");
 Students2 = new Student1(2,"Amar");
 s1.display();
 s2.display();
  }
}
Compile     :      javac Student1.java
Run           :      java Student1
Output       : 
Id is :1
Name is :Sravan
Id is :2
Name is :Amar
-------------------------------------------------------------------
2. this keyword on methods
  • By using this keyword we can call current class methods.
-------------------------------------------------------------------
Program         :        this keyword
Program name  :        One.java
Output            : 
      method is invoked

class One
{
public void method1()
{
     System.out.println("method is invoked");
}
    public void method2()
{
this.method1();
}

public static void main(String args[])
{
One o=new One();
o.method2();
}
}
Compile     :      javac One.java
Run           :      java One
Output      : 
method is invoked
-------------------------------------------------------------------
Note 
  • If we didn't write this keyword then compiler will place this keyword implicitly.
-------------------------------------------------------------------
3. this keyword on constructor
  • By using this keyword we can call current class methods.
-------------------------------------------------------------------
Program         :        this keyword
Program name  :        Two.java
Output            : 
       default constructor
       int param constructor

class Two
{
      Two()
      {
          System.out.println("default constructor");
      }
      Two(int i)
      {
          this();
          System.out.println("int param constructor");
      } 

      public static void main(String args[])
      {
          Two t=new Two(10);
      }
}

Compile     :      javac Two.java
Run           :      java Two
Output      :  
                       default constructor
int param constructor
-------------------------------------------------------------------
Thanks for your time.

Nireekshan