Home » Java programming language

this keyword and this() method in Java



Here we are going to learn about this keyword and this() method in java? What are the usage of this keyword and this() method?
Submitted by Preeti Jain, on February 28, 2018

Java 'this' keyword

  • this is a keyword introduced in java.
  • With the help of this keyword, we can access instance variable, with this keyword if instance variable name and local variable name of the method or constructor are the same.

Example:

class ThisInstanceVariable{
	String str;
	
	ThisInstanceVariable(String str){
		this.str = str;
	}

	public void print(){
		System.out.println(str);
	}
	
	public static void main(String[] args){
		ThisInstanceVariable tiv = new ThisInstanceVariable("My Name Is Preeti jain");
		tiv.print();
	}
}

Output

D:\Java Articles>java ThisInstanceVariable
My Name Is Preeti jain
  • this keyword resolve the problem of ambiguity if name of instance variable and local variable of the methods are the same.
  • this keyword can pass as a parameter in the method call . It represents to pass the current object.
  • this keyword can pass as a parameter in the constructor call if we are calling other constructor of the same class.
  • this keyword can be used to call current class method.

Example:

class MethodCallByThis{

	MethodCallByThis(){
		this.print();
	}

	public void print(){
		System.out.println("Welcome in the print method");
	}
	
	public static void main(String[] args){
		MethodCallByThis mcbt = new MethodCallByThis();
	}
}

Output

D:\Java Articles>java MethodCallByThis
Welcome in the print method

Java 'this()' method

  • this() method introduced in java.
  • this() method can be used to call another constructor of the current class.

Example:

class ConstructorCallByThis{
	String str;

	ConstructorCallByThis(){
		this("calling string constructor");
	}
	
	ConstructorCallByThis(String s){
		System.out.println("Welcome in string constructor");
	}
	
	public static void main(String[] args){
		ConstructorCallByThis ccbt = new ConstructorCallByThis();
	}
}

Output

D:\Java Articles>java ConstructorCallByThis
Welcome in string constructor





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.