The this keyword in java

The this keyword in java

The this keyword refer to current class object in java . this keyword can be used for following 

  • this() can be used to invoke current class constructor
  • this can be used to invoke current class method
  • this can be used to return current class object
  • this can be used to refer current class instance variable 
  • this can be used to pass an argument in method call
  • this can be used to pass an argument in constructor call


1) this: to refer current class instance variable

class Student{  

int rollno;  

String name;  

float fee;  

Student(int rollno,String name,float fee)

{  

this.rollno=rollno;  

this.name=name;  

this.fee=fee;  

void display()

{

System.out.println(rollno+" "+name+" "+fee); 

}public static void main(String args[]){  

Student s1=new Student(1,"anil",50f);  

Student s2=new Student(2,"sunil",60f) ;    

s1.display();  

s2.display();  

}  

}

2) this: to refer current class constructor invoke

class Student
{  
Student()
{
System.out.println("hello a");
}  

Student(int x)
{  
this();   // current class constructor invoke
System.out.println(x);  
}
public static void main(String args[])
{  
Student a=new Student(10);  
}  
}

3) this: to refer current class method invoke

class Student
{  
void demo()
{
System.out.println("hello a");
}  

void display()
{  

        System.out.println("hello display");

this.demo();    
}
public static void main(String args[])
{  
Student a=new Student();

               a.display();  
}  
}

Comments

Popular posts from this blog

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver