Day30 : this reference
The 'this' Reference
'this' is a special implicit reference which is available in parameter list of every instance in Java. Whenever we call any non-static Or instance method of any class then java automatically passes the addresses of the calling object as argument to that method. Within this method java itself declares a special reference in the parameter list and this reference is called "this" reference. so, we can say that every non - static method(including constructor) always knows the address of its calling object via its "this" reference.
"this" is also a keyword in java.
Benefit of using "this"
By using "this" we can resolve the overlapping of data member/instance var of the class done by local var of the method with same name.
public class Emp{
private int id;
private String name;
private double salary;
public Emp(int id, String name, double salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public void show(){
System.out.println("id = " +id);
System.out.println("name = "+name);
System.out.println("salary = " + salary);
}
Driver Class:
public class useEmp{
public static void main(String [ ] args)
Emp e = new Emp(101, "Dinesh", 50000);
e.show();
}
Perform Constructor Chaining
In Java we're allowed to call one constructor from another constructor of the same class and this is called constructor chaining.
We normally do this to avoid duplicate code and call one constructor from another constructor.
But when we do this we make use of "this()". However these are two restriction we must remember.
- Constructor chaining can only be done by constructor and not by other methods of the class.
- The line use for constructor chaining must be the first line of the body of the constructor.
public class Box{
private int l,b,h;
public Box(){
this(0);
}
public Box(int s)
{
this(s,s,s);
}
public Box(int i,int j, int k)
{
l = i;
b = j;
h = k;
}
public void show(){
System.out.println("length = " +l);
System.out.println("breadth = "+b);
System.out.println("height = "+h);
}
}
Driver Class:
public class UseBox
{
public static void main(String [ ] args)
{
Box B1 = new Box();
Box B2 = new Box(10);
Box B3 = new Box(5,7,9);
B1.show();
B2.show();
B3.show();
}
}
Comments