1) The this keyword can be used to refer current class instance variable.
| If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. |
Understanding the problem without this keyword
| Let's understand the problem if we don't use this keyword by the example given below: |
class Student10{
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[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
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[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Output:0 null
0 null
| In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable. |
Solution of the above problem by this keyword
//example of this keyword
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Karan
222 Aryan
class base
{
base()
{
System.out.println("i am base class");
}
base(int i)
{
System.out.println("i am perametrised");
}
}
class derived extends base
{
String s;
int a;
public static void main(String args[])
{
derived x=new derived("hello",4);
}
derived (int i)
{
super(i);
System.out.println("the value of i ->"+i);
}
derived (String s,int a)
{
//this(i);
System.out.println("the value of s="+s);
System.out.println("the value of a="+a);
}
}
This keyword in java
ReplyDeletegreat, keep sharing