☰ See All Chapters |
Java this keyword
this is a keyword in java.
this is a reference variable which refers to the current object.
this keyword is used to access the members of the class within the same class and can be used only to access instance members.
this cannot be used to access static members of the class. this also cannot be used in static context.
Usage of java this keyword
this keyword can be used to access the instance variables
this keyword can be used to access the constructors
this keyword can be used to access the methods
Accessing the instance variables using this
this keyword is used to resolve the conflicts between instance variables and local variables.
package com.java4coding;
public class Demo { int height; int width; int length;
public Demo ( ) { }
public Demo (int height, int width, int length ) { this.height = height; this.width = width; this.length = length; }
public void setValues (int height, int width, int length) { this.height = height; this.width = width; this.length = length; } } |
Accessing the constructor using this
this() can be used to invoke another constructor from one constructor within the same class.
this() can be used for invoking current class constructor (constructor chaining).
this() will be used for doing constructor chaining within the same class.
When you are using this() to invoke a constructor then it should be the first statement inside the constructor.
package com.java4coding;
public class Demo { int height; int width; int length; int depth;
public Demo ( ) { }
public Demo (int height, int width, int length ) { this.height = height; this.width = width; this.length = length; }
public Demo (int height, int width, int length, int depth ) { this(height, width, length );//This will invoke above constructor this.depth = depth; } } |
Accessing the methods using this
this can be used to invoke another method from a method.
package com.java4coding;
public class Demo { int height; int width; int length; int depth;
public void setValues (int height, int width, int length) { this.height = height; this.width = width; this.length = length; }
public void setValues (int height, int width, int length, int depth) { this.setValues(height, width, length );//This will invoke above method this.depth = depth; } } |
All Chapters