Hi All, I am not understanding the Concept of Passing objects as parameters.I have copied the exmaple from the following book (Java2 Complete Reff by Patrick Naughton). Please explain me more about this code.
I've copied the above function since this is where you say you are confused. I'll discuss some of the issues involved, but if I'm unclear on any point or don't hit something you want to know more about, please feel free to ask for clarifiction. The first thing I think you should understand is that this equals() method "belongs" to the Test class. When you call the method, there is always one implied parameter that is invisibly passed to the method. This parameter is called "this" and is a reference to the object which you use to call the method. For example,
When equals begins execution, "this" refers to the same object as ob1. Next, the equals() method also defines an explicit parameter, called o, which refers to a Test object. Using the above example, o will refer to the same object as ob2. Now let's look at this line of code:
o.a refers to the member variable a in the object named o. (Remember that o refers to the object that was explicitly passed as a parameter -- ob2 in our example.) a refers to the member a of the object named this. If you specified this.a, it means the same thing. In fact, I prefer using this.a when refering to a member variable because it avoids confusion with local variables. The same concepts apply to o.b and b. I hope this clears up some things for you. If you have any more questions, please come back to ask them. Keep coding! Layne
I must admit the code does look a bit confusing. "o" isn't a particularly good character to use for a variable name because it looks a bit like a zero. Using the "this" keyword to show explicitly that the references to "a" and "b" are in the current object might also make it clearer. And there's no real reason to have an if.. else construct. You could rewrite the function more clearly as:
Yep. Minor point: You shouldn't start your variable names with capital letters. It is a Java coding convention that variables start with lower-case letters - i.e. your "PassedObj" should be "passedObj" instead. David
It looks like you are getting it. Keep coming back with more questions. The official Java Coding Conventions can be found at http://java.sun.com/docs/codeconv/. They are available online or for download. [ February 19, 2004: Message edited by: Layne Lund ]