Monday, December 19, 2011

Java: Pass by value or Pass by reference

Java: Pass by value or Pass by reference?
Short: Pass by value

This is basically for memory optimization, as I would like to think. Primitive data types have specific length whereas objects do not. In the memory both of these are stored in a continuous sequence of bits. The primitive types are stored from, if you will, low number to high number whereas objects are stored from higher number to lower in order to find the continuous free blocks.

It is generally agreed that primitives are passed by value and objects (memory address) are referenced. However, even the object references are passed by value.

In C# you can actually pass by reference and the original object also gets modified.
E.g
void passMe(ref OrginialObj obj)
{
obj = ....;//original object is modified even after the method returns
}


 

Interface v Abstract Class (in my own words)

Interface based programming works very closely with DI (P2I or program to interface). The container will push the concrete implementation at runtime so the code is loosely coupled. It also promotes Test Driven Development. Why? You can by-pass the configuration files that might be looking to resolve the resources.

As for difference between abstract classes and interface, both are basically contracts that need to be followed by the implementing classes but interface allows the contract (of the methods) to be "upto" the developer. It also means the developer can now implement as many interfaces as necessary. I would like to think of Abstract Classes as "more strict". Programatically, you would be allowed to implement from only one abstract class, neither can be instantiated, and abstract classes can have concrete method definitions.