Sunday, November 15, 2015

this keyword in java with example

In this post you will learn about this keyword in java. This is one of the important keyword in java.  This is a reference variable that refers  to the current object.this is a reference variable to the current object

Use of this keyword:

  1. this keyword can be used to refer current class instance variable
  2. this() can be used to invoke current class constructor
  3. this can be passed as an argument in the method call
  4. this can be passed as an argument constructor call

Understand the problem without using this keyword:

Example:

class Student{
int id;
String name;
Student(int id,String name)
{
id=id;
name=name;
}
void display(){
System.out.println(id+" "+name);
               }
public static void main(String args[]){
Student s1=new Student(15,"raju");
Student s2=new Student(16,"john");
s1.display();
s2.display();
}
}

Output:

              0 null
              0 null

Note:

In above example, formal arguments and instance variables are same that is way we are using this keyword to distinguish between instance variable and local variable

So solution of the above example is below:

class Student{
int id;
String name;
Student(int id,String name)
{
 this.id=id;
 this.name=name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1=new Student(15,"raju");
Student s2=new Student(16,"john");
s1.display();
s2.display();
}
}

Output:

 15 raju
 16 john


             




this can be used to invoked current class constructor:  


  • the this() constructor call can be used to invoke current class constructor 
  • this approach is better if you have many constructors in the class and want to reuse that constructor
EX:
class Student1{
int id;
String name;
Student1(){
System.out.println("default constructor is called");

Student1(int id,String name){
this();//it is used to invoked current class constructor
this.id=id;
this.name=name;
}
Student1(int id,String name,String address){
this(id,name);//no need to initialize id,name
this.city=city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
public static void main(String args[]){
Student1 st=new Student1(33,"micky");
Student1 st1=new Student1(34,"jocky","poland");
st.display();
st1.dispaly();
}
}

Output:

                 33 micky null
                 34 jocky poland

this is also  used to call method of that class:


Ex :                      
public void getName(){
System.out.println("learnprogramingbyluckysir");
}
public void dispaly(){
this.getName();
System.out.println();
}



1 comment:

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...