References in OOP

banner_references.jpg

1. What is a reference? #

Reference, a concept of OOP language, is a variable contains a value of the address which refers (or points) to where in memory an object is stored.
Reference.jpg
To make it easier to understand, let me give an example: Your house is somewhere in the city, and a friend cannot know it until you give him a visit card which contains the house’s address. In this case, the card is a reference and the house is an actual space or value in memory.

However, be careful with the another concept, Pointer in C++ programming. Actually, reference and pointer seem to do some same or similar things. Especially, we can use them for accessing an object.
MemoryAddressContent.png
Pointer, on the other hand, is different from reference in some cases. If you are interested in C++ programming, please check more here

2. Where is a reference? #

References are stored in a Stack and the objects which they refer to are stored in a Heap.
For example:

Integer baz = 123;
String bar = "123";


stack_and_heap.gif

3. What types of reference? #

There are 4 main types of references: Strong, Weak, Soft and Phantom references, in term of how strongly reachable the reference is.

In the next post, I would like to introduce some useful cases in which being aware of how to use reference can help us a lot to save memory and avoid the Out Of Memory error (OOM).

 
16
Kudos
 
16
Kudos

Now read this

What is a Garbage Collector?

1. What is it? # A garbage collector (GC), a concept of computer science, simply is a program or process which is run by OS, in order to free some space of the device’s memory which was allocated before and now is not used anymore. In... Continue →