Lec 4 - Passing Object in Java
Lec 4 - Passing Object in Java
Primitive Parameters
…
Point p = new Point(10, 20);
addTen(p);
System.out.println(p.x + “,“ + p.y);
…
void addTen(Point pa) {
pa.x = pa.x + 10;
pa.y = pa.y + 10;
}
Modify a Parameter Value
Before calling: 5
After calling: 6
The point here is that what we pass exactly is
a handle of an object, and in the called
method a new handle created and pointed to
the same object.
Now when more than one handles tied to the
same object, it is known as aliasing.
From the example above you can see that
both p and a refer to the same object
To prove this try to System.out.println(p) and
System.out.println(a) you will see the same
address.
This is the default way Java does when
passing the handle to a called method, create
alias.
When you pass argument just to manipulate
its value and not doing any changes to it, then
you are safe.
9-18
The equals Method
The Stock class has an equals method.
If we try the following:
9-
19
The equals Method
Instead of using the == operator to compare two Stock
objects, we should use the equals method.
public boolean equals(Stock object2)
{
boolean status;
9-
20
Methods That Copy Objects
9-21
Copy Constructors
A copy constructor accepts an existing object of the same
class and clones it
9-
22
END