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
Post a Comment