What is the use of the special variable "this" if I can use the full name to refer to the Object. For example: "Object.name" OR Object.age"
Asked
Active
Viewed 367 times
-12
-
`this` is a key word. Not variable. – Suresh Atta Jan 28 '14 at 09:26
-
What's with all the duplicates of that specific question at the moment? Is there a test going on somewhere or something? ;) – Henrik Aasted Sørensen Jan 28 '14 at 09:27
-
2Dear Lord never access your variables like that. Also, never name your object starting upper case! There are some rules for accessing data and naming conventions. Please read on them – diazazar Jan 28 '14 at 09:27
-
The object you are referring to doesn't have a name yet - it is "this" object, that's the use of it. You don't know the name of the object, but can call the current object with `this`. – sashkello Jan 28 '14 at 09:30
-
There is no such thing as "the full name" of an Object. You are confusing objects and classes. – Ingo Jan 28 '14 at 09:30
-
1@Henrik Lol. I'm self-teaching myself JAVA from a Textbook, and finding "this" particular section tricky so there. I guess I should delete this question because of so many down votes :/ But its the only way to learn; by asking questions. – user3243076 Jan 28 '14 at 10:19
-
2@user3243076 Another way is by searching for existing answers. – Mike B Jan 28 '14 at 15:11
3 Answers
3
Objects don't have a "name" and you can't refer to an instance of a class by mentioning just the class. Try to write this code:
Object o = new Object();
System.out.println(o.toString());
System.out.println(Object.toString());
and see what errors you get from the compiler.
Marko Topolnik
- 188,298
- 27
- 302
- 416
2
this refers to the current instance, not the class. The main use is in constructors and setters, where the argument shadows a data member.
E.g.:
public class MyClass {
int someInt;
public MyClass (int someInt) {
// Save the someInt argument to the someInt member
this.someInt = someInt;
}
}
Mureinik
- 277,661
- 50
- 283
- 320
1
this keyword is used to refer current object
and Object.name type instructions are used when your variable is a static type
Raj Kumar
- 532
- 4
- 8