In this article we will see what is 'this' keyword in Java and usage of 'this' keyword with example.

In Java "this" keyword is used to refer the current object, and can be used to call current class constructor.

It can be passed as an argument in the method call, it can be passed as argument in the constructor call and it can be used to return the current class instance.

1) 'this' as an argument in the constructor call

public class Dog {
	String name;

	// parameterised constructor
	Dog(String name) {
		this.name = name;
	}
	
	// default constructor
	Dog() {
	}
}
In the example above, we have used 'this' inside the constructor body which implies, assign the value of 'name' parameter to current instance's name. This will assign the passed value as name of the newly created instance.

Above class can be instantiated as:
Dog dog = new Dog("Bull Dog");
Here "Bull Dog" will be assigned as name of 'dog' object of 'Dog' class.

2) 'this' as an argument in the method call

In the below example getName(Dog dog) method requires an instance of Dog class:
public class Dog {
	String name;

	// parameterised constructor
	Dog(String name) {
		this.name = name;
	}
	// method
	public void getName(Dog dog){
		System.out.println(dog.name);
	}
}
getName(Dog dog) can be called in following two ways.
	public void name(){
		getName(this);
	}

	public void name(){
		Dog dog2 = new Dog("Black Dog");
		getName(dog2);
	}
The first call will print value of 'name' from the calling object, while second call will print "Black Dog" irrespective of which object is calling name();

3) 'this' used to return the current class instance.

In the below example, getInstance() will return the instance which is calling this method.
public class Dog {
	// not a constructor
	Dog getInstance() {
		return this;
	}
}
In this article we have see what is 'this' keyword in Java and usage of 'this' keyword with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java