• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Objects as Parameters - an example

 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks, i'm having great difficulty wrapping my head around what's going on in the code below. In particular, with the method:-
boolean equals(Test o)
What is this 'o' doing? What does it refer to??? What is its data type (can't see where it's been defined)? etc....
If somebody could also explain to me, the whole point of this listing (ok, it's from a chapter in a boox on Methods and Classes). I am at a loss.
Cheers in advance.

 
Joe Ess
Bartender
Pie
Posts: 9266
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Jensen:

Test ob1 = new Test(100, 22);
Test ob2 = new Test (102, 24);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));


o is a variable, a particular instance of Test. It takes on whatever value is passed to the method. For example, in the code above the o in the equals() method takes on the value of ob2, a Test object with a=102 and b=24.
 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joe Ess:

o is a variable, a particular instance of Test. It takes on whatever value is passed to the method. For example, in the code above the o in the equals() method takes on the value of ob2, a Test object with a=102 and b=24.

Uhm, ok, but the start of the method states:-
boolean equals(Test o)
So, by specifying 'o', we should be accepting one paramater, not 2 (102 and 24), surely?
 
Joe Ess
Bartender
Pie
Posts: 9266
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Jensen:
So, by specifying 'o', we should be accepting one paramater, not 2 (102 and 24)

We specify the Class of the argument and a variable. The class is Test and the variable name is o. A class is a collection of data and behavior. In our particular instance, Class Test contains two integers: a and b, and a couple of methods, main and equals. The equals method compares the object we called the method on to the one passed in as an argument. That's why in this line from the equals method:
if (o.a == a && o.b == b) return true;
we have 2 variables named a. o.a is the integer passed into equals through the instance of Test named o. In the example I specified above we call the equals method like this:
ob1.equals(ob2)
inside the equals method, a = 100 and o.a = 102. I changed the values from what you had before to make it a little clearer.
[ November 14, 2003: Message edited by: Joe Ess ]
 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers for your help - my problem's sorted, (for now!)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic