Thursday, 17 August 2017

This Keyword in Java

This  keyword can be use in this ways :
  • to refer current class instance variable
  • to call current class method
  • to call current class constructor
  • This can be used as an argument in the method call.
  • This can be used as argument in the constructor call.
  • This can be used to return the current class instance from the method.


To refer current class instance variable :

Code
class Student
{
     String name;
     int rollno;
     int age;
     void get(String name,int rollno,int age)
     {
                this.name = name;
                this.rollno = rollno;
                this.age = age;
    }
    void display()
    {
                System.out.println("Name is "+name);
                System.out.println("rollno is "+rollno);
                System.out.println("rollno is "+age);                  
    }
}
class school
{
    public static void main(String args[])
    {
                Student stu = new Student();
                stu.get("technews",80,21);
                stu.display();
    }
               
}

Output:
Name is technews
rollno is 80
rollno is 21

In the above example, arguments and instance variables are same. So, we use this keyword to differentiate local variable and instance variable.

To include current class method :

This keyword can also be used within Methods to call another Method from same Class.

Code
class demo_this
{
                 
    public void getName()
    {
                System.out.println("Tech news n career");
    }

    public void display()
    {
       this.getName();
      System.out.println();
    }
}
class example
{
   public static void main(String args[])
   {
                demo_this dt = new demo_this();
                dt.getName();
                dt.display();
   }
               
}
Output:
Tech news n career
Tech news n career

To include current class constructor :

This is a keyword in Java. It can be used within the Method or constructor of Class.

 It (this) workings as a reference to the exits Object whose Method or constructor is being called.  

This keyword can be used to refer to any member of the current object from within an instance Method or a constructor.

Code
class web
{
 private String name;
 public web()
 {
//oveloaded constructor is called.
  this("java tutprial technews n career");   
 }
 public web(String n)
 {
//member is initialized using this.
  this.name=n;  
  System.out.println(name);
 }
 public static void main(String args[])
                {
                                web w = new web();
                }
}
Output:
java tutprial technews n career


In this post we learned about this keyword in java.thw use of this keyword I hope it is very useful.

0 comments:

Post a Comment