What's the the difference if I were to use "this.x=y" instead of just "x=y"?
All I know is that this refers to the object created from the class.
Also what's the difference if I were to use "this.method()" as compared to creating a new class like so, "Class cs = new Class(); cs.method()"

Last question...
What is an interface? I've read some articles on it and it says something about extending classes. How do you use the method when what's inside it is just like calling a method? Also are there any detailed tutorials which teaches about interface and how to use it to pass a function as an argument?

BTW, if you know any good blogs on Java, please share.


8 Years
Discussion Span
Last Post by JamesCherrill

Your answer to first question.
1.this.x=y vs x=y
well x=y simply means u are assigning the value of y to x.No probs.

2.But this.x=y.'this' keyword is used to tell the JVM that u are referring to the instance variable belonging to a that particular class.eg:
class Example
int x;
Example(int x)
this x=x;

Above pgm if i had not used 'this' keyword there was no way fr the JVM to find out which value to be assigned to which variable.Both the variables have the same name(x).Generally 'this' is used in constructors.

You can understand a lot after reading the book by Kathy Sierra.
I hope this helps u out


Previous answer is 90% right, but, as defined in the Java language definition, the JVM has no problem deciding which variable to use.
Declaring x as a parameter "masks" or "hides" the declaration of the instance variable x, so an unqualified use of x in that method is a use of the parameter. So in the example
this.x = x;
this.x is an unambigious use of the instance variable, and
= x; is an unambiguous use of the parameter

Re methods:
The new class example makes no sense - probably confusion of "class" vs "instances of class". If this is what was intended:
this.someMethod(); // where this is an instance of SomeClass, vs
new SomeClass.someMethod();
In the first case the method will execute using the instance variables from the current instance ("this"). In the second case it will use the instance variables from a different (new) instance.

Interfaces are too big a topic to ask anyone to write you a tutorial. Here's a good place to start:
followed by:

Edited by JamesCherrill: n/a


Thanks for your responses guys.

So does that mean if I were to create a few instances of a class, using "this" would refer specifically to that instance, which means that their fields might all be different?


1. If you create few instances of a class, each instance has its own variables (unless the variable is declared "static"), which can be, probably will be, different.
"this" always refers to the current instance.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.