Related
Normally, I use this in constructors only.
I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.
However, I don't know that what the real meaning of this is in Java and what will happen if I use this without dot (.).
this refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like this:
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Then calling frobnicate() on new MyThisTest() will print
1
42
MyThisTest a=42
So effectively you use it for multiple things:
clarify that you are talking about a field, when there's also something else with the same name as a field
refer to the current object as a whole
invoke other constructors of the current class in your constructor
The following is a copy & paste from here, but explains very well all different uses of the this keyword:
Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
this is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
This invokes the constructor of the same java class which has two parameters.
this is used to pass the current java instance as parameter
obj.itIsMe(this);
Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
this can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by
Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.
To be complete, this can also be used to refer to the outer object
class Outer {
class Inner {
void foo() {
Outer o = Outer.this;
}
}
}
It refers to the current instance of a particular object, so you could write something like
public Object getMe() {
return this;
}
A common use-case of this is to prevent shadowing. Take the following example:
public class Person {
private final String name;
public Person(String name) {
// how would we initialize the field using parameter?
// we can't do: name = name;
}
}
In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
}
Quoting an article at programming.guide:
this has two uses in a Java program.
1. As a reference to the current object
The syntax in this case usually looks something like
this.someVariable = someVariable;
This type of use is described here: The 'this' reference (with examples)
2. To call a different constructor
The syntax in this case typically looks something like
MyClass() {
this(DEFAULT_VALUE); // delegate to other constructor
}
MyClass(int value) {
// ...
}
This type of use is described here: this(…) constructor call (with examples)
In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.
public class MyDialog extends JDialog implements ActionListener
{
public MyDialog()
{
JButton myButton = new JButton("Hello");
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
System.out.println("Hurdy Gurdy!");
}
}
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName then by definition it's not a global variable - it's a variable specific to this particular instance.
It refers to the instance on which the method is called
class A {
public boolean is(Object o) {
return o == this;
}
}
A someA = new A();
A anotherA = new A();
someA.is(someA); // returns true
someA.is(anotherA); // returns false
The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):
Public class test{
test(int a) {
this.a=a;
}
Void print(){
System.out.println(a);
}
Public static void main(String args[]){
test s=new test(2);
s.print();
}
}
Thats it. the Output will be "2".
If We not used the this keyword, then the output will be : 0
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank method in the Car class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this reserved word so you don't have to add it, it's a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).
In summary.
Objects are defined by classes and have methods and variables
The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
The implicit parameter is the object the method is called from in this case "audi".
The java compiler automatically adds the this reserved word, adding it is a matter of preference
this cannot be used without a dot(.) this is syntactically invalid
this can also be used to distinguish between local variables and global variables that have the same name
the this reserve word also applies to methods, to indicate a method belongs to a particular object.
Instance variables are common to every object that you creating. say, there is two instance variables
class ExpThisKeyWord{
int x;
int y;
public void setMyInstanceValues(int a, int b) {
x= a;
y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
}
class Demo{
public static void main(String[] args){
ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();
obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);
}
}
if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method.
How do you think JVM correctly assign the values for every object?
there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;
public void setMyInstanceValues(int a, int b) {
this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
this.y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
(I know Im late but shh Im being the sneaky boi you never saw me)
The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:
Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use
object.field
Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use
this.field
The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this:
(Hah, get it? this? Hehe .... just me? okay :( I'll leave now)
public String Name;
//Constructor for {object} class
public object(String Name){
Name = Name;
}
That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:
public String Name;
//Constructor for {object} class
public object(String Name){
this.Name = Name;
}
This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.
To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.
this is a reference to the current object: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
this can be used inside some method or constructor.
It returns the reference to the current object.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where
(double x,double y) are double values passed from different class to assign values to current class .
A quick google search brought this result: Link
Pretty much the "this" keyword is a reference to the current object (itself).
I was also looking for the same answer, and somehow couldn't understand the concept clearly. But finally I understood it from this link
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to a current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.
Check the examples in the link for a clear understanding
If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.
class Example{
int assign;// instance variable
Example(int assign){ // variable inside constructor
this.assign=assign;
}
}
Hope this helps.
In Java "this" is a predefined variable. If we use "this" in method that's mean we are getting the reference (address) of the currently running object. For an example.
this.age ---> age of the currently running object.
I would like to share what I understood from this keyword.
This keyword has 6 usages in java as follows:-
1. It can be used to refer to the current class variable.
Let us understand with a code.*
Let's understand the problem if we don't use this keyword by the example given below:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
output:
111 ankit 5000
112 sumit 6000
2. To invoke the current class method.
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello Natasha
hello Mandy
3. to invoke the current class constructor. It is used to constructor chaining.
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello ABCD
10
4. to pass as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
The method is invoked
5. to pass as an argument in the constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:-
10
6. to return current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:-
Hello
Also, this keyword cannot be used without .(dot) as it's syntax is invalid.
As everyone said, this represents the current object / current instance. I understand it this way,
if its just "this" - it returns class object, in below ex: Dog
if it has this.something, something is a method in that class or a variable
class Dog {
private String breed;
private String name;
Dog(String breed, String name) {
this.breed = breed;
this.name = name;
}
public Dog getDog() {
// return Dog type
return this;
}
}
The expression this always refers to the current instance.
In case of constructors, the current instance is the freshly allocated object that's currently being constructed.
In case of methods, the current instance is the instance on which you have called the method.
So, if you have a class C with some method m, then
during the construction of a fresh instance x of C, the this inside of the constructor will refer to x.
When x is an instance of C, and you invoke x.m(), then within the body of m, this will refer to the instance x.
Here is a code snippet that demonstrates both cases:
public class Example {
static class C {
public C whatDoesThisInConstructorReferTo;
public C() {
whatDoesThisInConstructorReferTo = this;
}
public C whatDoesThisInMethodReferTo() {
return this;
}
}
public static void main(String args[]) {
C x = new C();
System.out.println(x.whatDoesThisInConstructorReferTo == x); // true
System.out.println(x.whatDoesThisInMethodReferTo() == x); // true
}
}
Regarding other syntactical elements that are unrelated to the this-expression:
The . is just the ordinary member access, it works in exactly the same way as in all other circumstances, nothing special is happening in case of this.
The this(...) (with round parentheses) is a special syntax for constructor invocation, not a reference.
Normally, I use this in constructors only.
I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.
However, I don't know that what the real meaning of this is in Java and what will happen if I use this without dot (.).
this refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like this:
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Then calling frobnicate() on new MyThisTest() will print
1
42
MyThisTest a=42
So effectively you use it for multiple things:
clarify that you are talking about a field, when there's also something else with the same name as a field
refer to the current object as a whole
invoke other constructors of the current class in your constructor
The following is a copy & paste from here, but explains very well all different uses of the this keyword:
Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
this is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
This invokes the constructor of the same java class which has two parameters.
this is used to pass the current java instance as parameter
obj.itIsMe(this);
Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
this can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by
Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.
To be complete, this can also be used to refer to the outer object
class Outer {
class Inner {
void foo() {
Outer o = Outer.this;
}
}
}
It refers to the current instance of a particular object, so you could write something like
public Object getMe() {
return this;
}
A common use-case of this is to prevent shadowing. Take the following example:
public class Person {
private final String name;
public Person(String name) {
// how would we initialize the field using parameter?
// we can't do: name = name;
}
}
In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
}
Quoting an article at programming.guide:
this has two uses in a Java program.
1. As a reference to the current object
The syntax in this case usually looks something like
this.someVariable = someVariable;
This type of use is described here: The 'this' reference (with examples)
2. To call a different constructor
The syntax in this case typically looks something like
MyClass() {
this(DEFAULT_VALUE); // delegate to other constructor
}
MyClass(int value) {
// ...
}
This type of use is described here: this(…) constructor call (with examples)
In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.
public class MyDialog extends JDialog implements ActionListener
{
public MyDialog()
{
JButton myButton = new JButton("Hello");
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
System.out.println("Hurdy Gurdy!");
}
}
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName then by definition it's not a global variable - it's a variable specific to this particular instance.
It refers to the instance on which the method is called
class A {
public boolean is(Object o) {
return o == this;
}
}
A someA = new A();
A anotherA = new A();
someA.is(someA); // returns true
someA.is(anotherA); // returns false
The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):
Public class test{
test(int a) {
this.a=a;
}
Void print(){
System.out.println(a);
}
Public static void main(String args[]){
test s=new test(2);
s.print();
}
}
Thats it. the Output will be "2".
If We not used the this keyword, then the output will be : 0
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank method in the Car class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this reserved word so you don't have to add it, it's a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).
In summary.
Objects are defined by classes and have methods and variables
The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
The implicit parameter is the object the method is called from in this case "audi".
The java compiler automatically adds the this reserved word, adding it is a matter of preference
this cannot be used without a dot(.) this is syntactically invalid
this can also be used to distinguish between local variables and global variables that have the same name
the this reserve word also applies to methods, to indicate a method belongs to a particular object.
Instance variables are common to every object that you creating. say, there is two instance variables
class ExpThisKeyWord{
int x;
int y;
public void setMyInstanceValues(int a, int b) {
x= a;
y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
}
class Demo{
public static void main(String[] args){
ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();
obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);
}
}
if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method.
How do you think JVM correctly assign the values for every object?
there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;
public void setMyInstanceValues(int a, int b) {
this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
this.y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
(I know Im late but shh Im being the sneaky boi you never saw me)
The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:
Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use
object.field
Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use
this.field
The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this:
(Hah, get it? this? Hehe .... just me? okay :( I'll leave now)
public String Name;
//Constructor for {object} class
public object(String Name){
Name = Name;
}
That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:
public String Name;
//Constructor for {object} class
public object(String Name){
this.Name = Name;
}
This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.
To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.
this is a reference to the current object: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
this can be used inside some method or constructor.
It returns the reference to the current object.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where
(double x,double y) are double values passed from different class to assign values to current class .
A quick google search brought this result: Link
Pretty much the "this" keyword is a reference to the current object (itself).
I was also looking for the same answer, and somehow couldn't understand the concept clearly. But finally I understood it from this link
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to a current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.
Check the examples in the link for a clear understanding
If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.
class Example{
int assign;// instance variable
Example(int assign){ // variable inside constructor
this.assign=assign;
}
}
Hope this helps.
In Java "this" is a predefined variable. If we use "this" in method that's mean we are getting the reference (address) of the currently running object. For an example.
this.age ---> age of the currently running object.
I would like to share what I understood from this keyword.
This keyword has 6 usages in java as follows:-
1. It can be used to refer to the current class variable.
Let us understand with a code.*
Let's understand the problem if we don't use this keyword by the example given below:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
output:
111 ankit 5000
112 sumit 6000
2. To invoke the current class method.
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello Natasha
hello Mandy
3. to invoke the current class constructor. It is used to constructor chaining.
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello ABCD
10
4. to pass as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
The method is invoked
5. to pass as an argument in the constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:-
10
6. to return current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:-
Hello
Also, this keyword cannot be used without .(dot) as it's syntax is invalid.
As everyone said, this represents the current object / current instance. I understand it this way,
if its just "this" - it returns class object, in below ex: Dog
if it has this.something, something is a method in that class or a variable
class Dog {
private String breed;
private String name;
Dog(String breed, String name) {
this.breed = breed;
this.name = name;
}
public Dog getDog() {
// return Dog type
return this;
}
}
The expression this always refers to the current instance.
In case of constructors, the current instance is the freshly allocated object that's currently being constructed.
In case of methods, the current instance is the instance on which you have called the method.
So, if you have a class C with some method m, then
during the construction of a fresh instance x of C, the this inside of the constructor will refer to x.
When x is an instance of C, and you invoke x.m(), then within the body of m, this will refer to the instance x.
Here is a code snippet that demonstrates both cases:
public class Example {
static class C {
public C whatDoesThisInConstructorReferTo;
public C() {
whatDoesThisInConstructorReferTo = this;
}
public C whatDoesThisInMethodReferTo() {
return this;
}
}
public static void main(String args[]) {
C x = new C();
System.out.println(x.whatDoesThisInConstructorReferTo == x); // true
System.out.println(x.whatDoesThisInMethodReferTo() == x); // true
}
}
Regarding other syntactical elements that are unrelated to the this-expression:
The . is just the ordinary member access, it works in exactly the same way as in all other circumstances, nothing special is happening in case of this.
The this(...) (with round parentheses) is a special syntax for constructor invocation, not a reference.
I have a function multi2 which returns inner class Inner as an Object.
What happens to a - where is it saved and how can I access it?
public class C {
private static Object multi2(final int a) {
class Inner {
public int hashCode() {
return 2*a;
}
}
return new Inner(); // What happens to a?
// Who allocates a?
// Can I Access a?
}
public static void main(String[] args) {
Object o = multi2(6);
System.out.println("o.hashCode() = " + o.hashCode());
o = multi2(4);
System.out.println("o.hashCode() = " + o.hashCode());
}
}
What happens at the implementation level is that a copy of the value of a is saved in a synthetic instance variable declared in the compiled version of the C.Inner class.
The value of a is passed to the compiled Inner constructor via an extra parameter.
The C.Inner.hashCode method uses the value of the synthetic variable. Accessing a in the source code of Inner.hashCode is transformed into accessing the corresponding synthetic variable in the compiled code.
The variable in the outer scope must be final1. The synthetic variable must be final2 in the Inner class. This maintains the illusion that (potentially) multiple instances of the Inner class are seeing the same a variable. (They aren't, but since the variable(s) can't be changed, it is not possible for the code of the inner class to tell the difference.)
If you use javap to look at the bytecodes for the compiled example, you will see the mechanisms used to implement this in the outer and the inner classes.
1 - or effectively final from Java 8 onwards.
2 - If a could be mutated by an Inner method, then two Inner instances with the same outer class need to share a mutable variable whose lifetime is (now) longer than the stackframe for a multi2 call. That entails somehow turning a from stack variable into something that lives on the heap. It would be expensive and complicated.
You have defined the class Inner inside the function so the scope of the class will be
restricted with in the method. And your function is static so it will be live as long as the class definition is loaded. You have override the hashCode function inside the InnerClass so every time you are calling the multi2(param) you are creating the hashCode for the instance of InnerClass and returning the instance of the InnerClass.
So as for you questions, please correct me if i am wrong.
What happens to a ?
a is with in the scope of your static method, so it will be live as long as the class definition is loaded.
Who allocates a?
scope of a is restricted inside the static method and static method does not require instance to access it but as for the static method/variable allocation, i think it depends on JVM.
Can I Access a?
No you cannot access a from outside you static method, it is restricted with in your static method.
Since the "a" is a local parameter, you could use a different approach to read the "a" value:
public class C {
public static Object multi2(final int a) {
return new Inner(a);
}
public static void main(String[] args) {
Object o = multi2(6);
System.out.println("o.hashCode() = " + o.hashCode());
System.out.println("o.getA() = " + ((Inner) o).getA());
o = multi2(4);
System.out.println("o.hashCode() = " + o.hashCode());
System.out.println("o.getA() = " + ((Inner) o).getA());
}
}
class Inner{
public int valueA;
public Inner(int a)
{
valueA = a;
}
public int getA() {
return valueA;
}
public int hashCode() {
return 2*valueA;
}
}
I wanted to know what was actually happening, so I compiled your code and looked at the bytecode output.
Basically what happens is the compiler adds in a constructor to your class 'Inner'. It also adds a single parameter to that constructor which takes 'a'. If your multi2() method was NOT static then there would probably also be a parameter to take 'this' where 'this' is the instance of 'C' that multi2() is executing on. BUT since we're in static context, there is no 'this'.
The compiler adds a private final field to your class 'Inner' and sets that private field using the value passed via the constructor. The compiler also converts
new Inner()
into
new Inner(a)
Hashcode then accesses the private field containing the value for a.
If 'a' was an object instead of a primitive, then it would be the same way, but a reference would be passed through instead of an actual number value.
How do you access this variable? Well you access it with reflections, but there are many problems:
1) You don't know the name of the field made by the compiler, so you can only get the name by looking at the bytecode. Don't trust decompilers as they might change the name. You gotta look at the bytecode yourself to find out.
2) The compiler probably marks the field as final, which means even if you can get reflections to access the field for you, you won't be able to update it.
3) It is entirely up to the compiler to figure out field names. Field names could change between builds depending on the compiler and it's mood.
Inner is a so called local class. a is a parameter passed to the method multi2 and accessable within that scope. Outside of that method, you cannot access a.
Sorry if this is a repeat, i've tried looking for the answer to my question but could not come across the answer I'm after.
I'm very new at Java (literally started yesterday) and I am trying to understand why if I declare a variable in my class and then assign a value to it in a void method, the value associated with that variable persists beyond the method's scope. My (very) limited understanding of methods is that they have their own scope and I thought the only way to access any variable changes that had been made within a method was to return them at the end of the method. Is this not the case?
Each method in a class will inherit any attribute (variable) or any method that directly belongs to that class. Say
public class Bicycle {
public int gear;
public int speed;
// the Bicycle class has
// two methods
public void setGear(int newValue) {
gear = newValue;
}
public void speedUp(int increment) {
speed += increment;
}
}
Let's get the setGear method
public void setGear(int newValue) {
gear = newValue;
}
As you can see, I can access the 'gear' attribute because it belongs to the Bicycle class. The parameter '(int newValue)' belongs to this method exclusively, meaning I can only access this variable inside this method, like this:
public void setGear(int newValue) {
newValue = gear;
//this wouldn't make much sense logic wise, but it is
//valid code since I can use newValue only inside the setGear method
speedUp(10);
//the method 'speedUp' belongs to the bicycle class, so I can use
//it inside another method belonging to the same class
}
Alternatively, I can use the this keyword to say that I am referring class attributes, like this:
public void setGear(int gear) {
this.gear = gear;
//I am telling the method that the class attribute 'gear' will
//receive my parameter value 'gear'
//this is useful when my parameter variable name has the same
//name as my class attribute
}
Edit: forgot to give credit to the oficial oracle docs https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
The answer to this is a bit more complex.
First start to distinguish a method from a function.
A method operates on an object instantiated by calling the constructor of the class (e.g. MyClass obj = new MyClass();). From this point, your object has a state expressed by it's member variables (all variables that are not declared static in your class).
Methods (as part of the object) may change this state (unless the corresponding variables are declared final).
To be able to to so, a method inherits the scope of the class, but the variables are bound to the instance of the object, on which the method is called.
So for instance:
public class MyClass {
private int a = 0;
public void aplusplus() {a++;}
}
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.aplusplus(); // the a of obj1 is now 1
obj2.aplusplus(); // the a of obj2 is now 1
obj1.aplusplus(); // the a of obj1 is now 2
But beware! There is also a concept called hiding.
If you declare a local variable within the body of a method, it hides the class member variable. Accessing the variable by name results in accessing the local variable, instead of the member variable. This is particuallry interesting when implementing setter methods for private members, where usually the argument of the method (which is a local variable) is named exactly as the member variable. To still access the member variable, you can use this.variablename. For instance:
public class MyClass {
private int a = 0;
public void aplusplus() {a++;}
public void setA(int a) {this.a = a;}
}
You say in your question that you have declared a variable in your class. This means that any value the variable gets set to, (during method invocations), will persist across method invocations. The variable is part of this object, and as such, is referred to as an instance variable.
If you declare variables inside method definitions, they are inside the scope of the method. They are part of this.yourMethod(). These variables are said to be local to the method. You can only use these variables inside the method. The this object does not know they exist.
Normally, I use this in constructors only.
I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.
However, I don't know that what the real meaning of this is in Java and what will happen if I use this without dot (.).
this refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like this:
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Then calling frobnicate() on new MyThisTest() will print
1
42
MyThisTest a=42
So effectively you use it for multiple things:
clarify that you are talking about a field, when there's also something else with the same name as a field
refer to the current object as a whole
invoke other constructors of the current class in your constructor
The following is a copy & paste from here, but explains very well all different uses of the this keyword:
Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
this is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
This invokes the constructor of the same java class which has two parameters.
this is used to pass the current java instance as parameter
obj.itIsMe(this);
Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
this can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by
Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.
To be complete, this can also be used to refer to the outer object
class Outer {
class Inner {
void foo() {
Outer o = Outer.this;
}
}
}
It refers to the current instance of a particular object, so you could write something like
public Object getMe() {
return this;
}
A common use-case of this is to prevent shadowing. Take the following example:
public class Person {
private final String name;
public Person(String name) {
// how would we initialize the field using parameter?
// we can't do: name = name;
}
}
In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
}
Quoting an article at programming.guide:
this has two uses in a Java program.
1. As a reference to the current object
The syntax in this case usually looks something like
this.someVariable = someVariable;
This type of use is described here: The 'this' reference (with examples)
2. To call a different constructor
The syntax in this case typically looks something like
MyClass() {
this(DEFAULT_VALUE); // delegate to other constructor
}
MyClass(int value) {
// ...
}
This type of use is described here: this(…) constructor call (with examples)
In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.
public class MyDialog extends JDialog implements ActionListener
{
public MyDialog()
{
JButton myButton = new JButton("Hello");
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
System.out.println("Hurdy Gurdy!");
}
}
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName then by definition it's not a global variable - it's a variable specific to this particular instance.
It refers to the instance on which the method is called
class A {
public boolean is(Object o) {
return o == this;
}
}
A someA = new A();
A anotherA = new A();
someA.is(someA); // returns true
someA.is(anotherA); // returns false
The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):
Public class test{
test(int a) {
this.a=a;
}
Void print(){
System.out.println(a);
}
Public static void main(String args[]){
test s=new test(2);
s.print();
}
}
Thats it. the Output will be "2".
If We not used the this keyword, then the output will be : 0
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank method in the Car class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this reserved word so you don't have to add it, it's a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).
In summary.
Objects are defined by classes and have methods and variables
The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
The implicit parameter is the object the method is called from in this case "audi".
The java compiler automatically adds the this reserved word, adding it is a matter of preference
this cannot be used without a dot(.) this is syntactically invalid
this can also be used to distinguish between local variables and global variables that have the same name
the this reserve word also applies to methods, to indicate a method belongs to a particular object.
Instance variables are common to every object that you creating. say, there is two instance variables
class ExpThisKeyWord{
int x;
int y;
public void setMyInstanceValues(int a, int b) {
x= a;
y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
}
class Demo{
public static void main(String[] args){
ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();
obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);
}
}
if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method.
How do you think JVM correctly assign the values for every object?
there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;
public void setMyInstanceValues(int a, int b) {
this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
this.y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
(I know Im late but shh Im being the sneaky boi you never saw me)
The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:
Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use
object.field
Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use
this.field
The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this:
(Hah, get it? this? Hehe .... just me? okay :( I'll leave now)
public String Name;
//Constructor for {object} class
public object(String Name){
Name = Name;
}
That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:
public String Name;
//Constructor for {object} class
public object(String Name){
this.Name = Name;
}
This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.
To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.
this is a reference to the current object: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
this can be used inside some method or constructor.
It returns the reference to the current object.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where
(double x,double y) are double values passed from different class to assign values to current class .
A quick google search brought this result: Link
Pretty much the "this" keyword is a reference to the current object (itself).
I was also looking for the same answer, and somehow couldn't understand the concept clearly. But finally I understood it from this link
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to a current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.
Check the examples in the link for a clear understanding
If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.
class Example{
int assign;// instance variable
Example(int assign){ // variable inside constructor
this.assign=assign;
}
}
Hope this helps.
In Java "this" is a predefined variable. If we use "this" in method that's mean we are getting the reference (address) of the currently running object. For an example.
this.age ---> age of the currently running object.
I would like to share what I understood from this keyword.
This keyword has 6 usages in java as follows:-
1. It can be used to refer to the current class variable.
Let us understand with a code.*
Let's understand the problem if we don't use this keyword by the example given below:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
output:
111 ankit 5000
112 sumit 6000
2. To invoke the current class method.
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello Natasha
hello Mandy
3. to invoke the current class constructor. It is used to constructor chaining.
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello ABCD
10
4. to pass as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
The method is invoked
5. to pass as an argument in the constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:-
10
6. to return current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:-
Hello
Also, this keyword cannot be used without .(dot) as it's syntax is invalid.
As everyone said, this represents the current object / current instance. I understand it this way,
if its just "this" - it returns class object, in below ex: Dog
if it has this.something, something is a method in that class or a variable
class Dog {
private String breed;
private String name;
Dog(String breed, String name) {
this.breed = breed;
this.name = name;
}
public Dog getDog() {
// return Dog type
return this;
}
}
The expression this always refers to the current instance.
In case of constructors, the current instance is the freshly allocated object that's currently being constructed.
In case of methods, the current instance is the instance on which you have called the method.
So, if you have a class C with some method m, then
during the construction of a fresh instance x of C, the this inside of the constructor will refer to x.
When x is an instance of C, and you invoke x.m(), then within the body of m, this will refer to the instance x.
Here is a code snippet that demonstrates both cases:
public class Example {
static class C {
public C whatDoesThisInConstructorReferTo;
public C() {
whatDoesThisInConstructorReferTo = this;
}
public C whatDoesThisInMethodReferTo() {
return this;
}
}
public static void main(String args[]) {
C x = new C();
System.out.println(x.whatDoesThisInConstructorReferTo == x); // true
System.out.println(x.whatDoesThisInMethodReferTo() == x); // true
}
}
Regarding other syntactical elements that are unrelated to the this-expression:
The . is just the ordinary member access, it works in exactly the same way as in all other circumstances, nothing special is happening in case of this.
The this(...) (with round parentheses) is a special syntax for constructor invocation, not a reference.