Class passing it self
I have a class that creates the object of type Smo. The object then calls a static method from another class. The static method requires that I pass the object to it开发者_开发技巧 that is calling it. How do I designate the calling object as the parameter to pass.
For example:
class Smo {
Smo() {
}
void sponge() {
car.dancing(??????); //////< ----------- how do I refer to self?
}
void dance() {
//// do a little dance
}
}
class Car() {
Car() {
}
dancing(Smo smo) {
smo.dance();
}
}
Use the this
keyword.
car.dancing(this);
use the keyword this
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.
Use this
to have an object refer to itself. So,
car.dancing(this);
yup: car.dancing(this);
been there done (this) :D
精彩评论