Reading "Thinking in Java" by Bruce Eckel at the moment. Reached "this" keyword point. It's not clear for me how really objects and "this" work. Bruce Eckel in his book says:
If you have two objects of the same type called a and b, you might wonder how it is that you can call a method peel( ) for both those objects:
//: initialization/BananaPeel.java class Banana { void peel(int i) { /* ... */ } } public class BananaPeel { public static void main(String[] args) { Banana a = new Banana(), b = new Banana(); a.peel(1); b.peel(2); } } ///:~
If there’s only one method called peel( ), how can that method know whether it’s being called for the object a or b?
To allow you to write the code in a convenient object-oriented syntax in which you “send a message to an object,” the compiler does some undercover work for you. There’s a secret first argument passed to the method peel( ), and that argument is the reference to the object that’s being manipulated. So the two method calls become something like:
Banana.peel(a, 1); Banana.peel(b, 2);
So, when we create an object it has it own methods copied from the class.
A obj = new A();
obj.callMethod(); //<-- object uses it's own method, not the class, right?
And according to the book the methods of a class are shared somehow between all the objects created from this class.
How does this mechanism work in the result?
I don’t get this part: If you have two objects of the same type called a and b, you might wonder how it is that you can call a method peel( ) for both those objects. If there’s only one method called peel( ), how can that method know whether it’s being called for the object a or b?
What does it mean “only one method called peel()”
We have all the methods from the class created for each object. So we just call the method from the object.
What did Bruce Eckel mean?