Friday, December 12, 2014

Some basic concepts: class, object, reference, method and function, and badSwap ()

I decided to dig deeper to these concepts after my method failed to pass some value back to the main() method, twice...

Ok, start from the Method and Function.

Thanks to Stacks Overflow
A function is a piece of code that is called by name. It can be passed data to operate on and can optionally return data.
A method is a piece of code that is called by name that is associated with an object.
A method is implicitly passed for the object for which it was called. It is able to operate on data that is contained within the class.
Moreover, in C++, methods are called member functions. Languages like Java only have methods. Thus, functions would be analogous to static methods.
A method is able to operate on the private instance data declared as part of the class.

Class, Reference and Object
A class provides the blueprint for objects, an object is created from class.

For example, Point originOne = new Point(1, 2)

creates an object originOne  of the Point class. Without instantiation, i.e., Point originOne, we only declare a reference with no object, and no memory is assigned.

"new" operator instantiates  a class (creates an object) by allocating memory for a new object and returning a reference to that memory.
Initializing an object allows us to assign values to the variables of the object through constructors.

badSwap()
I wrote a swap() method the other day only to find out it didn't work. Today when I tried to pass a variable to another method, it didn't pass the correct value back to the main() method either. Thus I decided to figure out what is really going on.

In a nutshell, Java manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference, it passes them by value.

When you pass an object to a method, Java passes the reference of the object by value, which means the reference passed to the method are actually copies of the original references.

Point ptn 1 = new Point(1, 2);
Point ptn 2 = new Point(3, 4);

badSwap(Point p1, Point p2)
{
    Point tmp = p1;
    p1 = p2;
    p2 = tmp;
}

When ptn1 and ptn2 are passed to to badSwap(Point p1, Point p2), two other references ptn1_copy, ptn2_copy are actually passed. badSwap(Point p1, Point p2) swaps ptn1_copy and ptn2_copy. But when returns to the main() method, the original ptn1 and ptn2 are not swapped.
Thus, we cannot write a swap() function unless actual objects (e.g., with an array) are passed to the function.





No comments:

Post a Comment