Reputation: 107
Lets say you have some random class called Dude
, and you have some private instance variables and you have some get methods and a compareTo
method to say if one instance of the class has the same variables as another instance of the class and that's pretty much it. Well, lets say in some driver class, you make two Dude
objects, and you call them d1
and d2
.
Well, now you wanna compare the two and see if they have the same instance data, so you'd call d1.compareTo(d2);
Now, my question is, when creating the compareTo
method inside the dude class, you pass it one object as a parameter and the other one.....?
I'm thinking it would go something like this:
public boolean compareTo(Dude d){
if (this.getArbitraryVariable() == d.getArbitraryVariable()) return true
and so on.
But for that to work, you would have no clue what the currently executing object is, and the only logical explaination I can think of is that the "." operator makes whatever is to the left of it, the current executing object in the class. Is that right or no?
Upvotes: 0
Views: 82
Reputation: 3739
The dot operator not only gives you the current executing object , it can also give you the current executing class, which is how you use static methods and static variables.
For ex :-
staticClass.staticMethod();
Also you can use the dot operator for chaining. For ex
String finalValue=input.replaceAll("numbers","alphabets").substring(0,`32).trim();
Upvotes: 0
Reputation: 75565
That is not quite the correct intuition.
When you write d1.compareTo(d2);
, this compiles down to something closer to compareTo(d1,d2)
.
That is, when you call a method on an object, you basically pass the object as the first parameter implicitly.
When you are inside the method, you use the keyword this
to refer to the implicit object that was passed to the method.
Upvotes: 3