+ Start a Discussion
cvm_asishcvm_asish 

Usage of generic sObject Type

hello friends,

 

I have a doubt in "generic sObject Type" declaration. I was going through one PDF and I got the below example, but I didn't understand exactly what does it means.

 

Can someone clearly explain this with some simple example?Why for the contact its showing error? In which scenario this type of declaration required?

 

 

-------------------------------------------------------------------------------------------------------------------------------

Similar to the Web Services API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data type can be used in code that processes different types of sObjects.

The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:

sObject s = new Account();

You can also use casting between the generic sObject type and the specific sObject type. For example:

// Cast the generic variable s from the example above 
    
// into a specific account and account variable a 
    
Account a = (Account)s;
// The following generates a runtime error 
    
Contact c = (Contact)s;

DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.

 

-------------------------------------------------------------------------------------------------------------------------------

 

 

Thanks in advance.

 

Thanks

Asish

Message Edited by cvm_asish on 01-17-2010 11:36 PM
bob_buzzardbob_buzzard

The contact line will give an error as the code is attempting to cast an Account to a Contact, which is not valid.

 

If you are familiar with Java, you can think of sObject as an abstract superclass that allows your code to handle any type of Salesforce standard or custom object without having to know the actual type.  As it is an abstract type class, you can't instantiate an sobject, you have to instantiate a concrete subclass (contact, for example)/

 

I have used this type when creating my own custom lookup page - in that case, I want to carry out a query to retrieve all objects matching a search string (e.g. all Contacts containing bo*), but I want to return the results as a generic list of sObjects so that I don't have to explicitly handle each and every type of object that can be looked up. 

cvm_asishcvm_asish

okay, I got it............

 

Thanks a lot Bob for your reply.

 

thanks

Asish