Saturday, November 11, 2017

Memory Representations of Class & Objects in Java vs Javascript

Java objects and Class based Inheritance in Memory:
In Java, the concept of Templates called Class exists. The main purpose is to tell how to create an object of a class if requested during runtime by using 'new ();'. 

As you know, a class can inherit another class by using 'extends' and on and on..we can have any number of levels of inheritance. Note that each class directly or indirectly extends from root class called 'Object'. That means every object in java has a direct or indirect reference to Object's object instance.

While creating objects for classes, each object, its parent's object and all along till the root(Object's object)...all have their own copies in the memory.

Consider the following inheritance:
ModelSX --> BMW --> Car --> Vehicle --> Object
ModelVClass --> Benz --> Car --> Vehicle --> Object

ModelSX modelSX1 = new ModelSX();
ModelSX modelSX2 = new ModelSX();



As shown above, each single object has its own hierarchical copies of objects. The same applies for ModelVClass and any other class.



JavaScript objects and Prototype based Inheritance in Memory:
Predominantly there are 4 ways to create objects and one of them is via constructor

Here is how:
function Car(model,number,type){
this.model = model;
this.number = number;
this.type = type;
}
var bmwSX1 = new Car("SX1",1234,"SUV");

Executing above lines of code, Javascript creates not just one but 3 objects - Car Function object, Car Function's object, Car's Prototype object. Car Function object & Car Function's object linked via Car's Prototype object. Similarly if you create an Employee object using an Employee function constructor, the 3-object set is created in memory. Like in Class based inheritance, there is a root 3-object set exists - Object Function object, Object Function's object & Object's Prototype. Below figure depicts link between root(Object prototype) and other user defined objects...



As shown above, if user tries to access a property on an object say employee, Jsengine first looksup at employee object, if it doesn't find then it goes to employee's prototype, and if it is still not succeed then it searches in Object's prototype.

How to establish multilevel hierarchy:
Say if we have two objects - Employee and Manager. In order to make employee as manager's parent, link manager's prototype's __proto__ property pointing to employee's prototype. Then the following inheritance will be achieved..
Manager-> Employee -> Object 

No comments:

How J2EE components work together in any Container - Spring or Application Server

In a Spring+Jersey+Hibernate RESTful webapplication, we can spot various J2EE components - JTA, JPA, Java Bean Validation, JSON-B API for B...