Difference between assignment to object variable and class variable/attribute [duplicate] - java

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?

The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.
Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
{
private String name;
public void setName(String name) {
this.name = name;
}
}
Case 2: Using this as an argument passed to another object.
public class Foo
{
public String useBarMethod() {
Bar theBar = new Bar();
return theBar.barMethod(this);
}
public String getName() {
return "Foo";
}
}
public class Bar
{
public void barMethod(Foo obj) {
obj.getName();
}
}
Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
{
public Foo() {
this("Some default value for bar");
//optional other lines
}
public Foo(String bar) {
// Do something with bar
}
}
I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:
public class Outer {
protected int a;
public class Inner {
protected int a;
public int foo(){
return Outer.this.a;
}
public Outer getOuter(){
return Outer.this;
}
}
}

You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)
Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)

The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.

"this" is also useful when calling one constructor from another:
public class MyClass {
public MyClass(String foo) {
this(foo, null);
}
public MyClass(String foo, String bar) {
...
}
}

There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
You know foo is a variable declared in outer class Hello.
You know getStringFromSomewhere() is a method declared in outer class as well.
You know that bar belongs to World class, and s is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

this is useful in the builder pattern.
public class User {
private String firstName;
private String surname;
public User(Builder builder){
firstName = builder.firstName;
surname = builder.surname;
}
public String getFirstName(){
return firstName;
}
public String getSurname(){
return surname;
}
public static class Builder {
private String firstName;
private String surname;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setSurname(String surname) {
this.surname = surname;
return this;
}
public User build(){
return new User(this);
}
}
public static void main(String[] args) {
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
}
}

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

#William Brendel answer provided three different use cases in nice way.
Use case 1:
Offical java documentation page on this provides same use-cases.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this){
// Do some thing.
}
Use case 3:
Implementation of Builder pattern depends on use of this to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)

Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.

Following are the ways to use ‘this’ keyword in java :
Using this keyword to refer current class instance variables
Using this() to invoke current class constructor
Using this keyword to return the current class instance
Using this keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.

this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}

Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A {
private int i;
public A(int i) {
this.i = i; // this.i can be used to disambiguate the i being referred to
}
}
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method() clarifies that the call is made by this object.

this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO {
protected int i;
public void modify() {
i = 9;
}
public void thisModify() {
this.i = 9;
}
}
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m() {
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
}

With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window {
private Window parent;
public Window (Window parent) {
this.parent = parent;
}
public void addSubWindow() {
Window child = new Window(this);
list.add(child);
}
public void printInfo() {
if (parent == null) {
System.out.println("root");
} else {
System.out.println("child");
}
}
}
I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.
If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

Related

Is there a more specific reason to use "this" in Java other than style and readability? [duplicate]

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?
The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.
Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
{
private String name;
public void setName(String name) {
this.name = name;
}
}
Case 2: Using this as an argument passed to another object.
public class Foo
{
public String useBarMethod() {
Bar theBar = new Bar();
return theBar.barMethod(this);
}
public String getName() {
return "Foo";
}
}
public class Bar
{
public void barMethod(Foo obj) {
obj.getName();
}
}
Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
{
public Foo() {
this("Some default value for bar");
//optional other lines
}
public Foo(String bar) {
// Do something with bar
}
}
I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.
The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:
public class Outer {
protected int a;
public class Inner {
protected int a;
public int foo(){
return Outer.this.a;
}
public Outer getOuter(){
return Outer.this;
}
}
}
You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)
Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)
The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.
"this" is also useful when calling one constructor from another:
public class MyClass {
public MyClass(String foo) {
this(foo, null);
}
public MyClass(String foo, String bar) {
...
}
}
There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
You know foo is a variable declared in outer class Hello.
You know getStringFromSomewhere() is a method declared in outer class as well.
You know that bar belongs to World class, and s is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
this is useful in the builder pattern.
public class User {
private String firstName;
private String surname;
public User(Builder builder){
firstName = builder.firstName;
surname = builder.surname;
}
public String getFirstName(){
return firstName;
}
public String getSurname(){
return surname;
}
public static class Builder {
private String firstName;
private String surname;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setSurname(String surname) {
this.surname = surname;
return this;
}
public User build(){
return new User(this);
}
}
public static void main(String[] args) {
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
}
}
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
#William Brendel answer provided three different use cases in nice way.
Use case 1:
Offical java documentation page on this provides same use-cases.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this){
// Do some thing.
}
Use case 3:
Implementation of Builder pattern depends on use of this to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
Following are the ways to use ‘this’ keyword in java :
Using this keyword to refer current class instance variables
Using this() to invoke current class constructor
Using this keyword to return the current class instance
Using this keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A {
private int i;
public A(int i) {
this.i = i; // this.i can be used to disambiguate the i being referred to
}
}
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method() clarifies that the call is made by this object.
this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO {
protected int i;
public void modify() {
i = 9;
}
public void thisModify() {
this.i = 9;
}
}
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m() {
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
}
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window {
private Window parent;
public Window (Window parent) {
this.parent = parent;
}
public void addSubWindow() {
Window child = new Window(this);
list.add(child);
}
public void printInfo() {
if (parent == null) {
System.out.println("root");
} else {
System.out.println("child");
}
}
}
I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.
To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.
If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

In the following piece of code what does 'this' refer to? [duplicate]

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.

Variable Inheritance in Java

I have a Super class and a bunch of subclasses. I want to have one field that has the same name in every single subclass, but I do not want it to be defined in the super class, or at least I do not want to use that value. This is what I have right now
public abstract class Big {
public String tellMe = "BIG";
public Big() {}
public void theMethod() {
System.out.println ("Big was here: " + tellMe() + ", " + tellMe);
}
public String tellMe() {
return tellMe;
}
}
public class Little extends Big{
public String tellMe = "little";
public Little(){}
public String tellMe() {
return "told you";
}
public static void main(String [] args) {
Little l = new Little();
l.theMethod();
}
}
When I run Little, this is the output
Big was here: told you, BIG
I am not sure why 'told you' is printed out while tellMe refers to "BIG". How can both be true?
My problem is that I want the method tellMe() to be in Big, and to have the variable tellMe (that it will actually return) to be defined in all the subclasses. The only way I can get this to work is as I have written, by rewriting the tellMe() method in each subclass. But doesn't that defeat the whole purpose of inheritance??? Please help
EDIT: I do not use the constructor in my subclasses. All I want is a field that can be set in all subclasses and a method in the super that uses those values. I don't understand why this isn't possible because every subclass would have to implement it, so it would make sense... If this simply is not possible, let me know please
Fields are not virtual, unlike methods. For this reason, it is a bad idea to declare fields with the same name as a field in another class in the hierarchy. The field referred to in theMethod is always going to be from Big (i.e. when you declare a field with the same name, it just hides the old field when in the scope of the replacing class, but doesn't replace it).
One solution would be to override a method that gets the field from the current class:
In theMethod replace the tellMe field with getTellMe() and for all classes override getTellMe() to return the correct value (or the field that hides the superclass's field).
You can overwrite the value of Big.tellMe in the constructor of Little.
get rid of:
public String tellMe = "little";
and change the Little constructor to:
public Little(){
tellMe = "little";
}
at that point, you can get rid of Little.tellMe() also.
What you are doing is hiding the super class field, not overriding it, as the Java documentation states.
And it's also stated that it's not a good idea to do it.
So, the dynamic lookup won't work as for a method. If the variable is read from the son class, it will take "its" field value.
On the top class, the other one.
What you can override in Java is the behaviour, so what I would suggest is to
define a method
public String tellMe() {
return "Whatever";
}
that you can override in the subclasses to return whatever string you need.
Instead of defining tellMe inside of Big (since you said you do not want to define/use that value in Big) you can create a function in Big:
public abstract String tellMeString();
And define that in each subclass like so (for Little):
public String tellMeString()
{
return "Little";
}
Then theMethod can execute:
System.out.println ("Big was here: " + tellMe() + ", " + tellMeString());
In this case you wouldn't have to define a variable "tellMe" at all, you just override tellMeString in each subclass to return different Strings.
Fields are not inherited as you are expected. You can access the super class' field (unless it is private) from subclass. But you cannot "override" field. This is why tellMe used by method implemented in super class Big uses variable defined in the same class.
If you want inheritance use methods. For example you can implement method "tellMe()" that returns "BIG" in super class and "little" in subclass:
class Big {
protected String tellMe() {
return "BIG";
}
}
class Little {
#Override
protected String tellMe() {
return "Little";
}
}
Alternatively you can initialize variable tellMe in constructor:
class Big {
private String tellMe;
public Big() {
this("BIG");
}
protected Big(String tellMe) {
this.tellMe = tellMe;
}
protected String tellMe() {
return "BIG";
}
}
class Little {
public Little() {
super("Little");
}
}
Now new Little().tellMe() will return "Little": the variable in super class was initialized when constructing the object; the method defined in super class returned this variable.
Methods can be overridden, fields are visible at the scope where they're called.
static class Big {
String field = "BIG";
String bark() { return "(big bark)"; }
void doIt() {
System.out.format("field(%s) bark(%s)\n", field,bark());
}
void doIt2() {
System.out.format("2:field(%s) bark(%s)\n", field,bark());
}
}
static class Small extends Big {
String field = "small";
String bark() { return "(small bark)"; }
void doIt2() {
System.out.format("2:field(%s) bark(%s)\n", field,bark());
}
}
public static void main(String... args) {
Big b = new Big();
b.doIt();
b.doIt2();
Small s = new Small();
s.doIt();
s.doIt2();
}
Output is:
field(BIG) bark((big bark))
2:field(BIG) bark((big bark))
field(BIG) bark((small bark))
2:field(small) bark((small bark))
since doIt() is defined in the Big class, it will always see the Big version of field. doIt2() is defined in Big, but overridden in Small. The Big.doIt2() sees the Big version of field, the Small.doIt2() version sees the Small version of field.
As others have pointed out, it's a pretty bad idea to do this - a better approach is to set the new value in the subclass constructor, or to use a method which is overridden.

What use is the final modifer on method/constructor parameters

Hello
What use is the final modifier on a method/constructor parameter?
Ex:
class someClass {
private final double some; // I understand the use of final in this context, immutability etc..
public someClass(final double some) {
// I don't understand what purpose is served by making "some" final
this.some = some;
}
public void someMethod(final double some) {
// I don't understand what purpose is served by making "some" final
}
}
There are 2 main situations when you need it:
1) you want to use the parameter inside local class (usually, anonymous class), like:
public void foo(final String str) {
Printer p = new Printer() {
public void print() {
System.out.println(str);
}
};
p.print();
}
2) you like the style when every variable which is not modified is marked with the final word (it is generally a good practice to keep as much things immutable as possible ).
Well, the purpose is that you cannot asign the parameter with anything
public someClass(T some) {
some = null; //You can do this. Maybe you want to use the variable `some` later on in your constructor
}
public someClass(final T some) {
some = null; //You can't do this. If you want to reuse `some` you can't.
}
Useful? Not much. Normally you don't use arguments variables. But in some special situations you may want to be able to do it.
Anyway, if some does new someClass(mySome) , mySome will never be changed although inside the function you assign values to the argument. There is no such thing as pass-by-refrence in Java. Variables are primitives or references to objects, never the object itself.
From the point of view of the function, the some variable is a constant.
Another benefit would be to prevent variable reuse. That is to say "some" should be used for only one purpose.

What is the meaning of "this" in Java?

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.

Categories