function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Newbie10Newbie10 

Object declaration

Can somebody please explain what below code does

sobject s = new account();

Account a = (Account)s;
object obj = s;

a = (account)obj;

 

 

I am particularly interested in what happens at stack/heap when object obj = s happens.

 

i could see in developer console a [object Object] value for obj.But cannot figure what exactly happens internally or what is the purpose

 

 

Code source is Apex developer guide

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

Object is a completely generic type that can be anything (it doesn't have to be a SObject). For example you can assign an Integer or String to the "Object" type like so:

 

Object a = new Account();
System.debug(a);
a = 1;
System.debug(a);
a = 'Test';
System.debug(a);

SObject has to be referencing a table that exists in Salesforce (or generic SObject which has get and put methods on it)

All Answers

Sean TanSean Tan

You're just really casting the objects back and fourth... Some of this is based off assumption but I'm assuming the class hierachy would be something like this:

 

Object

SObject extends Object

Account extends SObject

 

Now to you're specific interest about what happens to the heap, nothing will happen. Like a lot of the other OOP languages, it is simply a memory pointer reference that you're assigning to different variables.

 

Try this code sample:

 

SObject s = new Account();
System.debug('Current Heap:::' + Limits.getHeapSize());

Account a = (Account)s;
System.debug('Current Heap:::' + Limits.getHeapSize());

Object obj = s;
System.debug('Current Heap:::' + Limits.getHeapSize());

a = (Account)obj;
System.debug('Current Heap:::' + Limits.getHeapSize());

Based off the trace statements nothing happens to the heap...

SurpriseSurprise

H sean ,

 

What is the difference between object and sobject.

 

Thanks

Sean TanSean Tan

Object is a completely generic type that can be anything (it doesn't have to be a SObject). For example you can assign an Integer or String to the "Object" type like so:

 

Object a = new Account();
System.debug(a);
a = 1;
System.debug(a);
a = 'Test';
System.debug(a);

SObject has to be referencing a table that exists in Salesforce (or generic SObject which has get and put methods on it)

This was selected as the best answer
SurpriseSurprise

By table you mean Objects.Thans for the nice info

Newbie10Newbie10

Thanks Sean

 

Just one more quick clarification

What is the difference between

 

Object obj =  (Account)s; and

 

Object obj = s;