class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
id=id;
name=name;
college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();
}
Output:
0 null null
0 null null
in the above program parameters and instance variables are same.so we by using this keyword we can solve this problem.
solution of the above problem using This keyword:
class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
this.id=id;
this.name=name;
this.college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();
}
Output:
1 Indhu TRML
2 Sindhu TRML
Important points of this keyword:
- This is final variable in java.so we can't assign values to the final.
- this=new Emp(); //Can't assign values to this.it will return compilation error.
Limitation of this keyword:
- "this" is applicable to only to the non static methods because static methods are not executed by any object
Instance of operator:
- Instance of operator is used to test whether that object is belong to that class type or not.
- If that object belongs to that class it returns true .otherwise it returns false.
- Instance of operator is also known as comparison operator.because it compares with the instance of type.
Program to instance of operator:
public class Employee{
public static void main(String args[]){
Employee e =new Employee();
System.out.println(e instanceof Employee);//true
}
}
Output:true
public class A{
public void show(){
System.out.println("This is class A");
}
public class B extends A{
public void show(){
System.out.println("This is class B");
}
public static void main(String args[]){
A a=new A();
System.out.println(a instanceof A);
System.out.println(a instanceof B);
}
}
Output:
true
false