{"id":1194,"date":"2022-02-25T16:38:09","date_gmt":"2022-02-25T16:38:09","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1194"},"modified":"2022-02-25T16:38:09","modified_gmt":"2022-02-25T16:38:09","slug":"java-this-keyword","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/25\/java-this-keyword\/","title":{"rendered":"Java this Keyword"},"content":{"rendered":"\n<p>In this article, we will learn about this keyword in Java, how and where to use them with the help of examples.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"introduction\">this Keyword<\/h2>\n\n\n\n<p>In Java, this keyword is used to refer to the current object inside a method or a constructor. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n    int instVar;\n\n    Main(int instVar){\n        this.instVar = instVar;\n        System.out.println(\"this reference = \" + this);\n    }\n\n    public static void main(String&#91;] args) {\n        Main obj = new Main(8);\n        System.out.println(\"object reference = \" + obj);\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>this reference = Main@23fc625e\nobject reference = Main@23fc625e<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we created an object named&nbsp;<var>obj<\/var>&nbsp;of the class&nbsp;<var>Main<\/var>. We then print the reference to the object&nbsp;<var>obj<\/var>&nbsp;and&nbsp;<code>this<\/code>&nbsp;keyword of the class.<\/p>\n\n\n\n<p>Here, we can see that the reference of both&nbsp;<var>obj<\/var>&nbsp;and&nbsp;<code>this<\/code>&nbsp;is the same. It means this is nothing but the reference to the current object.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Use of this Keyword<\/h2>\n\n\n\n<p>There are various situations where&nbsp;<code>this<\/code>&nbsp;keyword is commonly used.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"disambiguate-reference\">Using this for Ambiguity Variable Names<\/h2>\n\n\n\n<p>In Java, it is not allowed to declare two or more variables having the same name inside a scope (class scope or method scope). However, instance variables and parameters may have the same name. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyClass {\n    \/\/ instance variable\n    int age;\n\n    \/\/ parameter\n    MyClass(int age){\n        age = age;\n    }\n}<\/code><\/pre>\n\n\n\n<p>In the above program, the instance variable and the parameter have the same name: age. Here, the Java compiler is confused due to name ambiguity.<\/p>\n\n\n\n<p>In such a situation, we use this keyword. For example,<\/p>\n\n\n\n<p>First, let&#8217;s see an example without using&nbsp;<code>this<\/code>&nbsp;keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n\n    int age;\n    Main(int age){\n        age = age;\n    }\n\n    public static void main(String&#91;] args) {\n        Main obj = new Main(8);\n        System.out.println(\"obj.age = \" + obj.age);\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>obj.age = 0<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have passed&nbsp;<code>8<\/code>&nbsp;as a value to the constructor. However, we are getting&nbsp;<code>0<\/code>&nbsp;as an output. This is because the Java compiler gets confused because of the ambiguity in names between instance the variable and the parameter.<\/p>\n\n\n\n<p>Now, let&#8217;s rewrite the above code using&nbsp;<code>this<\/code>&nbsp;keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n\n    int age;\n    Main(int age){\n        this.age = age;\n    }\n\n    public static void main(String&#91;] args) {\n        Main obj = new Main(8);\n        System.out.println(\"obj.age = \" + obj.age);\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>obj.age = 8<\/samp><\/code><\/pre>\n\n\n\n<p>Now, we are getting the expected output. It is because when the constructor is called,&nbsp;<code>this<\/code>&nbsp;inside the constructor is replaced by the object&nbsp;<var>obj<\/var>&nbsp;that has called the constructor. Hence the&nbsp;<var>age<\/var>&nbsp;variable is assigned value&nbsp;<var>8<\/var>.<\/p>\n\n\n\n<p>Also, if the name of the parameter and instance variable is different, the compiler automatically appends this keyword. For example, the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n    int age;\n\n    Main(int i) {\n        age = i;\n    }\n}<\/code><\/pre>\n\n\n\n<p>is equivalent to:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n    int age;\n\n    Main(int i) {\n        this.age = i;\n    }\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"getter-setter\">this with Getters and Setters<\/h3>\n\n\n\n<p>Another common use of&nbsp;<code>this<\/code>&nbsp;keyword is in&nbsp;<em>setters and getters methods<\/em>&nbsp;of a class. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n   String name;\n\n   \/\/ setter method\n   void setName( String name ) {\n       this.name = name;\n   }\n\n   \/\/ getter method\n   String getName(){\n       return this.name;\n   }\n\n   public static void main( String&#91;] args ) {\n       Main obj = new Main();\n\n       \/\/ calling the setter and the getter method\n       obj.setName(\"Toshiba\");\n       System.out.println(\"obj.name: \"+obj.getName());\n   }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>obj.name: Toshiba<\/samp><\/code><\/pre>\n\n\n\n<p>Here, we have used&nbsp;<code>this<\/code>&nbsp;keyword:<\/p>\n\n\n\n<ul><li>to assign value inside the setter method<\/li><li>to access value inside the getter method<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"constructor-overloading\">Using this in Constructor Overloading<\/h2>\n\n\n\n<p>While working with&nbsp;<a href=\"https:\/\/www.programiz.com\/java-programming\/constructors#overloading\">constructor overloading<\/a>, we might have to invoke one constructor from another constructor. In such a case, we cannot call the constructor explicitly. Instead, we have to use&nbsp;<code>this<\/code>&nbsp;keyword.<\/p>\n\n\n\n<p>Here, we use a different form of this keyword. That is,&nbsp;<code>this()<\/code>. Let&#8217;s take an example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Complex {\n\n    private int a, b;\n\n    \/\/ constructor with 2 parameters\n    private Complex( int i, int j ){\n        this.a = i;\n        this.b = j;\n    }\n\n    \/\/ constructor with single parameter\n    private Complex(int i){\n        \/\/ invokes the constructor with 2 parameters\n        this(i, i); \n    }\n\n    \/\/ constructor with no parameter\n    private Complex(){\n        \/\/ invokes the constructor with single parameter\n        this(0);\n    }\n\n    @Override\n    public String toString(){\n        return this.a + \" + \" + this.b + \"i\";\n    }\n\n    public static void main( String&#91;] args ) {\n  \n        \/\/ creating object of Complex class\n        \/\/ calls the constructor with 2 parameters\n        Complex c1 = new Complex(2, 3); \n    \n        \/\/ calls the constructor with a single parameter\n        Complex c2 = new Complex(3);\n\n        \/\/ calls the constructor with no parameters\n        Complex c3 = new Complex();\n\n        \/\/ print objects\n        System.out.println(c1);\n        System.out.println(c2);\n        System.out.println(c3);\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>2 + 3i\n3 + 3i\n0 + 0i<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have used&nbsp;<code>this<\/code>&nbsp;keyword,<\/p>\n\n\n\n<ul><li>to call the constructor&nbsp;<code>Complex(int i, int j)<\/code>&nbsp;from the constructor&nbsp;<code>Complex(int i)<\/code><\/li><li>to call the constructor&nbsp;<code>Complex(int i)<\/code>&nbsp;from the constructor&nbsp;<code>Complex()<\/code><\/li><\/ul>\n\n\n\n<p>Notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(c1);<\/code><\/pre>\n\n\n\n<p>Here, when we print the object&nbsp;<var>c1<\/var>, the object is converted into a string. In this process, the&nbsp;<code>toString()<\/code>&nbsp;is called. Since we override the&nbsp;<code>toString()<\/code>&nbsp;method inside our class, we get the output according to that method.<\/p>\n\n\n\n<p>One of the huge advantages of&nbsp;<code>this()<\/code>&nbsp;is to reduce the amount of duplicate code. However, we should be always careful while using&nbsp;<code>this()<\/code>.<\/p>\n\n\n\n<p>This is because calling constructor from another constructor adds overhead and it is a slow process. Another huge advantage of using&nbsp;<code>this()<\/code>&nbsp;is to reduce the amount of duplicate code.<\/p>\n\n\n\n<p><strong>Note<\/strong>: Invoking one constructor from another constructor is called explicit constructor invocation.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"argument\">Passing this as an Argument<\/h3>\n\n\n\n<p>We can use&nbsp;<code>this<\/code>&nbsp;keyword to pass the current object as an argument to a method. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ThisExample {\n    \/\/ declare variables\n    int x;\n    int y;\n\n    ThisExample(int x, int y) {\n       \/\/ assign values of variables inside constructor\n        this.x = x;\n        this.y = y;\n\n        \/\/ value of x and y before calling add()\n        System.out.println(\"Before passing this to addTwo() method:\");\n        System.out.println(\"x = \" + this.x + \", y = \" + this.y);\n\n        \/\/ call the add() method passing this as argument\n        add(this);\n\n        \/\/ value of x and y after calling add()\n        System.out.println(\"After passing this to addTwo() method:\");\n        System.out.println(\"x = \" + this.x + \", y = \" + this.y);\n    }\n\n    void add(ThisExample o){\n        o.x += 2;\n        o.y += 2;\n    }\n}\n\nclass Main {\n    public static void main( String&#91;] args ) {\n        ThisExample obj = new ThisExample(1, -2);\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Before passing this to addTwo() method:\nx = 1, y = -2\nAfter passing this to addTwo() method:\nx = 3, y = 0<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, inside the constructor&nbsp;<code>ThisExample()<\/code>, notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>add(this);<\/code><\/pre>\n\n\n\n<p>Here, we are calling the&nbsp;<code>add()<\/code>&nbsp;method by passing this as an argument. Since this keyword contains the reference to the object&nbsp;<var>obj<\/var>&nbsp;of the class, we can change the value of&nbsp;<var>x<\/var>&nbsp;and&nbsp;<var>y<\/var>&nbsp;inside the&nbsp;<code>add()<\/code>&nbsp;method.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about this keyword in Java, how and where to use them with the help of examples. this Keyword In Java, this keyword is used to refer to the current object inside a method or a constructor. For example, Output: In the above example, we created an object named&nbsp;obj&nbsp;of the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[484],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1194"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1194"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1194\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1194"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1194"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}